execution of module bootstrap - zend-framework

Is there a way to have base bootstrap and module bootstrap?
this is my app structure
- application
- modules
- admin
- controllers
- Bootstrap.php
- public
- controllers
- Bootstrap.php
- Bootstrap.php
- libraries
When I test my app only the base bootstrap is executed.
I forced the execution of the modules bootstrap with this (in the base bootstrap):
$modules = array('admin', 'public');
foreach ($modules as $module) {
$path = APP_PATH . '/modules/' . $module . '/Bootstrap.php';
$class = ucfirst($module) . '_Bootstrap.php';
include_once $path;
$bootstrap = new $class($this);
$bootstrap->bootstrap();
}
Only with this I can execute bootstrap of modules.
Is there another way?

The module resource runs the module bootstraps. This is triggered by the presence of:
resources.modules[] = ""
in your application.ini, or you can manually bootstrap the modules in your main bootstrap class as you have.

Related

Route to static file in Mojo

I have small app based on mojolicious. And I have index.html in public dir. I want to have route to this file when user asks for '/'.
I wrote two solution, but I don't like them.
First solution - add simple controller.
sub stratup {
//...
$r->get('/')->to('general#index_html');
//...
}
package MyPackage::General;
use Mojo::Base 'Mojolicious::Controller';
use strict;
use warnings;
sub index_html {
my $self = shift;
$self->render_static('index.html');
return;
}
1;
Second solution - add hook
sub startup {
my $self = shift;
$self->hook(before_dispatch => sub {
my $self = shift;
if ($self->req->url eq '/') {
$self->req->url( Mojo::URL->new('/index.html') );
}
});
What I want:
$r->get('/')->to('/index.html');
or something like that.
P.S. I know, than usualy nginx/apache do it, but I use morbo to run code.
You want:
$r->get('...')->to(cb => sub {
my $c = shift;
$c->reply->static('index.html')
});
(As long as you're after Mojolicous 5.45 2014-09-26)
By far the simplest way is
get "/" => "index";
I'll dig this up from the graveyard, why not.
I found myself similarly trying to serve a static html file in a docker container that I had using to serve both a Mojolicious REST API and a Vue.js front end. After searching around and piecing sporadic information together, this is what seems to work for me.
** disclaimer: I have not fully tested this with Vue routing and other aspects as yet.
My directory structure:
/app
/app/script
/app/modules/ui
/app/modules/ui/dist
From the command line the app directory, using morbo to test:
morbo script/ui.pl
ui.pl script
#!/usr/bin/env perl
use Mojolicious::Lite -signatures;
use Mojo::File qw(curfile);
use v5.25;
my $app = app;
my $static = $app->static;
push #{$static->paths}, curfile->dirname->sibling('modules/ui/dist')->to_string;
any '/' => sub {
my $c = shift;
my $content = $static->file("/index.html")->slurp;
$c->render(text => $content);
};
$app->start;
Using a combo of information from https://metacpan.org/pod/Mojolicious::Static and basic routing information at https://docs.mojolicious.org/Mojolicious/Lite, I could get the vue.js index page to render as expected.
** UPDATED A DAY LATER **
As it turns out, there is an easier way, though not clearly documented. If you place the static files inside your public folder, you can use the default helpers included with Mojolicious to render the files. The documentation refers to it here, https://docs.mojolicious.org/Mojolicious/Guides/Rendering#Serving-static-files, but it's not very clear on how to make it happen.
I tooled around some, but it took browsing the code of Controller.pm of for Mojolicious to sort it out. This section of the POD led me to determine how to get the reply object:
=head2 helpers
my $helpers = $c->helpers;
Return a proxy object containing the current controller object and on which helpers provided by /app can be called. This includes all helpers from Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers.
# Make sure to use the "title" helper and not the controller method
$c->helpers->title('Welcome!');
# Use a nested helper instead of the "reply" controller method
$c->helpers->reply->not_found;
Based on this, I can drop my files into the public folder:
/app/public/index.html
Then modify my controller to match:
# https://docs.mojolicious.org/Mojolicious/Guides/Rendering#Serving-static-files
any '/' => sub {
my $c = shift;
$c->helpers->reply->static('index.html');
};

Default_Bootstrap overrides Admin_Bootstrap

In the Admin module installation Layout and Navigation of Default module
application/modules/default/Bottstrap.php
<?php
class Default_Bootstrap extends Zend_Application_Module_Bootstrap
{
protected function _initNavigation()
{
$layout = Zend_Layout::startMvc()->setLayout('layout');
$config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/navigation.xml','nav');
$navigation = new Zend_Navigation($config);
Zend_Registry::set('Zend_Navigation', $navigation);
}
}
application/modules/admin/Bottstrap.php
<?php
class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{
protected function _initNavigation()
{
$layout = Zend_Layout::startMvc()->setLayout('admin');
$config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/navadmin.xml','nav');
$navigation = new Zend_Navigation($config);
Zend_Registry::set('Zend_Navigation', $navigation);
}
}
application/configs/application.ini
;Modules
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.defaultModule = "default"
resources.modules[] =
resources.frontController.actionhelperpaths.Default_Controller_Helper = APPLICATION_PATH "/modules/default/controllers/helpers"
;Layout
resources.layout.layoutpath = APPLICATION_PATH "/layouts"
;View
resources.view.doctype = "HTML5"
resources.view.encoding = "UTF-8"
resources.view.contentType = "text/html; charset=UTF-8"
In a single-module application, layout and navigation are typically initialized in the single app-level bootstrap (sometimes by reference to an application resource plugin).
However, in a multi-module application, all the module bootstraps will run. Therefore, the last one that runs ends up overriding all the others.
For these types of tasks that depend upon knowing which module has been requested, you can use a front-controller plugin with routeShutdown() hook. Each module X could register its own plugins for navigation and layout that check if the requested module matches X. If not, bail early. If so, perform your initialization.
See MWOP's article on the subject of module bootstrapping for more details:
http://mwop.net/blog/234-Module-Bootstraps-in-Zend-Framework-Dos-and-Donts
a technique of loading a program into a computer by means of a few initial instructions which enable the introduction of the rest of the program from an input device.
start up (an Internet-based business or other enterprise) with minimal financial resources.

Zend Framework Bootstrap Issue

I have been working on a new installation of a Zend Framework application for a while now, and I cannot figure out what's going on. I have two custom action helpers I would like to use and I would like to initialize those in the bootstrap. But it seems as though my _init functions are not being called at all. In the index.php that starts the application I have:
require('Zend/Application.php');
$app = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH
.'/configs/application.ini');
$app->bootstrap()->run();
Here's what I have in the application.ini file:
[production]
appnamespace = "Application_Name"
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = "/home/user/website/includes/library/Application_Name/Resource/Bootstrap.php"
bootstrap.class = "Bootstrap"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.view[] =
autoloaderNamespaces[] = "Application_Name"
pluginPaths.Application_Name_Resource = "Application_Name/Resource"
I know the application is somewhat working because it is using a layout that I have and I can do things in the controllers and views and have it output to the page. I also know that it is at least looking at the Bootstrap file because I can make a PHP error happen when I leave out an end curly brace.
Here's a portion of my Bootstrap file:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _init()
{
Zend_Controller_Action_HelperBroker::addPrefix(new Application_Name_Controller_Action_Helper_ResourceInjector());
Zend_Controller_Action_HelperBroker::addPrefix(new Application_Name_Controller_Action_Helper_Em());
}
Any ideas why this would be or see something that I've messed up in my configuration? I've looked at tens of tutorials on how to configure Zend, and no one else seems to have this problem.
You're not using the helper broker correctly. addPrefix() is used to add pluginloader prefix paths, not actual classes.
If you want to add concrete helpers (to use their dispatch hooks presumably), then place something like this in your Bootstrap class
protected function _initActionHelpers()
{
$helper = new My_Helper;
Zend_Controller_Action_HelperBroker::addHelper($helper);
}
For regular, runtime helpers, you can easily add prefix paths in your config, eg
resources.frontController.actionHelperPaths.ProEquipTrack_Controller_Action_Helper = "ProEquipTrack/Controller/Action/Helper"
These will be automatically loaded by the broker at call time, eg (controller context)
$resourceInjector = $this->getHelper('ResourceInjector');
$em = $this->getHelper('Em');
or using the strategy pattern (direct() method)
$this->_helper->resourceInjector($arg1, $arg2 /*, etc */);
Doctrine Entity Manager
Do something like this in your Bootstrap class
protected function _initDoctrine()
{
// initialise and create entity manager
$em = // whatever
return $em;
}
You can now access the entity manager in your controllers using this
$em = $this->getInvokeArg('bootstrap')
->getResource('doctrine');

Get Loaded Config In Controller

How do i get the already loaded options in the controller file in a zend framework installation without creating a new Zend_Config([ ** ]); instance.
Once Zend_Application reads application.ini, the values are stored in bootstrap.
You may access them anywhere, without accessing the disk, or using the registry:
$front = Zend_Controller_Front::getInstance();
$bootstrap = $front->getParam('bootstrap');
if (null === $bootstrap) {
throw new My_Exception('Unable to find bootstrap');
}
$options = $bootstrap->getOptions();
In the controller you may also use $this->getInvokeArg('bootstrap');
I am not sure at all what you are asking but are you asking how to use configs set in application.ini from a controller? If so you should load that config in Zend_Registry in your bootstrap and then retrieve it in your controller.
So in bootstrap.php
protected function _initConfig() {
$config = new Zend_Config_Ini("../application/configs/application.ini");
Zend_Registry::set('config', $config);
}
The in your Controller
$myConfig = Zend_Registry::get('config');

Zend Layout - A "Smart" layout selector

I currently have Zend setup to look for a layout script in each module's view/scripts/layout.phtml file (ie: /application/modules/moduleName/scripts/layout.phtml). This is by setting layout[] to nothing (blank) in the application.ini file (resources.layout[] = )
The issue is that many modules may share the same layout. I don't want to copy the same exact layout into each module that uses it. I know I can set everything to use one layout script by setting a specific path like resources.layout.layoutpath = /layoutPath and everything would use /layoutpath/layout.phtml, and I know I can set individual pages (or whole Controllers, in the init) by using $this->_helper->layout->setLayout('foobaz');
The issue is that some modules will have different layouts, other than the 'standard' one, and I don't want to set it on a by Controller or by Action basis. I want to set it for the entire module, set in one place (or intuitively figured out by code/Zend automatically). Ideally, it would be setup how it is currently, but if a module doesn't have its own layout.phtml, it would use the default module's layout.
So... how do I do it?
There are several solutions, choose their own strategy
1 extending the action controller
class App_Controller_Action extends Zend_Controller_Action
{
public function init()
{
parent::init();
$moduleName = $this->getRequest()->getModuleName();
$layoutPath = APPLICATION_PATH . '/modules/' . $moduleName . '/layouts';
if (is_dir($layoutPath)) {
$this->view->addScriptPath($layoutPath);
}
}
}
and then do as usual IndexController extends App_Controller_Action ...
if layout file exists in APPLICATION_PATH . '/modules/' . $moduleName . '/layouts' directory - it will ne used instead of default layout
2 you can write frontcontroller plugin
class App_Controller_Plugin_ModuleSwitcher extends Zend_Controller_Plugin_Abstract
{
protected $_view = null;
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$moduleName = $request->getModuleName();
Zend_Layout::startMvc();
$layout = Zend_Layout::getMvcInstance();
$layout->setLayoutPath(APPLICATION_PATH . '/modules/' . $moduleName . '/layouts')->setLayout($moduleName);
return $request;
}
}
and dont forget to google for another solutions ;)
you can set own layout selector in few steps
step 1:
make module admin and default.
step 2:
create layout folder in each module as admin/layouts/scripts
and default/layouts/scripts
put into layout.phtml
step 3:
delete the layout.phtml file from Application/layouts/scripts.
step 4:
make the the Plugin folder inside library and make Plugin.php
as
class Plugin_Layout extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$layoutPath = APPLICATION_PATH . '/modules/' . $request->getModuleName() . '/layouts/scripts/';
Zend_Layout::getMvcInstance()->setLayoutPath($layoutPath);
}
}
step 5:
open Application/configs/Appication.ini file
and edit it
as
;resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.layout.layout = "layout"
;register your plugin
autoloaderNamespaces[] = "Plugin"
resources.frontController.plugins[] = "Plugin_Layout"
Step 6:
open bootstrap file Application/Bootstrap
put the code inside
protected function _initAutoload()
{
$loader = new Zend_Application_Module_Autoloader(array(
'namespace' => '',
'basePath' => APPLICATION_PATH . '/modules/'
));
return $loader;
}
protected function _initPlugins()
{
$this->bootstrap('frontcontroller');
$fc = $this->getResource('frontcontroller');
$fc->registerPlugin(new Plugin_Layout());
}
The quickest solution might be to create a symlink to point what would be a module layout file to the default layout. This won't work on Windows and is harder to maintain.
Better, create a method in your Bootstrap to set the layout.
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initLayoutScript(){
//ensure layout is setup
$this->bootstrap(array('layout', 'FrontController'));
$layout= $this->getResource('layout');
$front = $this->getResource('FrontController');
//do something with $layout and $front - set layout script/path etc based on request
//You could use file_exists to detect module layout scripts
}
}
See http://framework.zend.com/manual/en/zend.application.quick-start.html#zend.application.quick-start.resources for more details.
Finally, you could write your own application resource for use with Zend_Application.