Frontcontroller is not working properly in Zend Framework - zend-framework

I have created module(Admin) completely in zend framework. Now I want to start work in front end so I can manage my whole site from backend. But I am unable to getting solution for this. If I run my page at localhost, then it automatically call the css of backend and theme of backend with error message 'Exception Information', Here I am putting my application.ini file code
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
admin.bootstrap.path = APPLICATION_PATH "/modules/admin/Bootstrap.php"
admin.bootstrap.class = "Admin_Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 1
resources.session.name = "ZendSession"
;resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.use_only_cookies = true
resources.session.remember_me_seconds = 86400
resources.layout.layout = "layout"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
admin.resources.layout.layout = "admin"
admin.resources.layout.layoutPath = APPLICATION_PATH "/modules/admin/layouts/scripts"
resources.view.encoding = "UTF-8"
resources.view.basePath = APPLICATION_PATH "/views/"
resources.view[] =
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.modules[] =
resources.view[] =
admin.resources.view[] =
resources.db.adapter = Pdo_Mysql
resources.db.params.username = root
resources.db.params.password =
resources.db.params.dbname = myproject
resources.db.isDefaultTableAdapter = true
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
In bootstrap file I doesn't have initialization of any function or plugin
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
}
I have created separate bootsrap.php file for module admin like this:-
<?php
class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{
/*protected function _initAppAutoload()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'names pace' => 'admin',
'basePath' => APPLICATION_PATH . '/modules/admin/'
));
return $autoloader;
}*/
protected function _initDoctype()
{
global $adminModuleCssPath;
global $adminModuleJsPath;
$this->bootstrap( 'view' );
$view = $this->getResource( 'view' );
$view->headTitle('Projects for learning');
$view->headScript()->appendFile($adminModuleJsPath.'jquery-1.7.2.js');
$view->headScript()->appendFile($adminModuleJsPath.'jquery-ui.js');
$view->headScript()->appendFile($adminModuleJsPath.'tinybox.js');
$view->headScript()->appendFile($adminModuleJsPath.'common.js');
$view->headLink()->appendStylesheet($adminModuleCssPath.'jquery-ui.css');
$view->headLink()->appendStylesheet($adminModuleCssPath.'style.css');
$view->headLink()->appendStylesheet($adminModuleCssPath.'theme.css');
$view->headLink()->appendStylesheet($adminModuleCssPath.'tinybox.css');
$view->doctype( 'XHTML1_STRICT' );
//$view->navigation = $this->buildMenu();
}
protected function _initLayoutPlugin()
{
$layout = Zend_Controller_Front::getInstance();
$layout->registerPlugin(new Admin_Plugin_AdminLayout());
}
protected function _initAuthPlugin()
{
$checkAuth = Zend_Controller_Front::getInstance();
$checkAuth->registerPlugin(new Admin_Plugin_CheckAuth(Zend_Auth::getInstance()));
}
protected function _initRouter()
{
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route(
':module/:controller/:action/*',
array('module' => 'admin')
);
$router->addRoute('default', $route);
$usersRoute = new Zend_Controller_Router_Route_Regex(
':module/:controller/:action/(?:/page/(\d+)/?)?',
array(
'module' => 'admin',
'controller' => 'users',
'action' => 'index',
'page' => 1,
),
array(
'page' => 1,
)
);
$router->addRoute('users-index', $usersRoute);
}
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . "/modules/admin/views/helpers");
Zend_Controller_Action_HelperBroker::addPrefix('Admin_View_Helper');
}
/*protected function _initAutoload()
{
$autoloader = new Zend_Loader_Autoloader_Resource(array(
'namespace' => '',
'basePath' => APPLICATION_PATH."/modules/admin",
'resourceTypes' => array(
'form' => array(
'path' => 'forms',
'namespace' => 'Form',
),
'model' => array(
'path' => 'models',
'namespace' => 'Model',
),
)
));
return $autoloader;
}*/
}
Where I have made error, I don't know, I am new with Zend Framework, please anyone help me to resolve my this problem, so I can call my front site controllers and actions and manage it with backend module(admin)

Bootstrap classes for all modules are called on every request.
If you need to perform module-specific settings (initializing your view, for example), then register a front-controller plugin with a routeShutdown() hook. At that point in the dispatch cycle, you know which module is being called so you know how you want to configure your view.
For more information, see this answer and MWOP's post on ZF1 module bootstrapping.

Related

Zend Route - Remove parameter name from URL

I'm starting developing using Zend Framework and I have a question about routes. Is there a way to instead of having a URL like this:
www.mysite.com/newsletter/groups/edit/id/1
Have this:
www.mysite.com/newsletter/groups/edit/1
(without the parameter name id)
I already put this code to declare a custom route in my BootStrap file:
protected function _initRoutes()
{
$router = Zend_Controller_Front::getInstance()->getRouter();
/* Edit Groups */
$route = new Zend_Controller_Router_Route('groups/edit/:group_id',array('controller' => 'groups','action' => 'edit'));
$router->addRoute('group_edit', $route);
return $router;
}
Then in my view file I use this to echo the URL:
<?=$group->getName()?>
And the url is echoing the way I want:
Group 1
This is my application.ini:
[production]
appnamespace = "Application"
; Debug output
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
resources.frontController.params.displayExceptions = 0
;PHP Setings
phpsettings.date.timezone = "America/Sao_Paulo"
; Include path
includePaths.models = APPLICATION_PATH "/models"
includePaths.application = APPLICATION_PATH
includePaths.library = APPLICATION_PATH "/../library"
; Bootstrap
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
; Front Controller
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.env = APPLICATION_ENV
resources.frontController.actionHelperPaths.Action_Helper = APPLICATION_PATH "/views/helpers"
resources.frontController.moduleControllerDirectoryName = "actions"
;resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.defaultControllerName = "index"
resources.frontController.defaultAction = "index"
resources.frontController.defaultModule = "default"
;resources.frontController.baseUrl = "/newsletter"
;resources.frontController.returnresponse = 1
; Layout
resources.layout.layout = "layout"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
; Views
resources.view.helperPath = APPLICATION_PATH "/views/helpers"
resources.view.encoding = "UTF-8"
resources.view.basePath = APPLICATION_PATH "/views"
resources.view.scriptPath.Default = APPLICATION_PATH "/views/scripts"
resources.view.doctype = "HTML5"
resources.view.contentType = "text/html;charset=utf-8"
resources.view.helperPathPrefix = "Views_Helpers_"
resources.view.filterPathPrefix = "Views_Filters_"
resources.db.adapter = "PDO_SQLITE"
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
resources.frontController.throwExceptions = true
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.dbname = "newsletter"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.isDefaultTableAdapter = true
resources.db.params.charset = utf8
My complete Boostrap file:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctype()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype('XHTML1_STRICT');
}
/**
* Init Autoloader
*/
protected function _initAutoload()
{
$loader = Zend_Loader_Autoloader::getInstance();
$loader->setFallbackAutoloader(true);
}
/**
* Adiciona alguns routers
*/
protected function _initRoutes()
{
$router = Zend_Controller_Front::getInstance()->getRouter();
/* Edit Groups*/
$route = new Zend_Controller_Router_Route('/groups/edit/:groupId',array('controller' => 'group','action' => 'edit'));
$router->addRoute('group_edit', $route);
return $router;
}
}
My index.php (inside public) file:
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
->run();
The problem is, when I click to open this page (the edit group page) I get this error:
Fatal error: Uncaught exception 'Zend_Controller_Router_Exception' with message 'group_id is not specified' in C:\xampp\htdocs\fuhrmann\newsletter\library\Zend\Controller\Router\Route.php:354 Stack trace: #0 C:\xampp\htdocs\fuhrmann\newsletter\library\Zend\Controller\Router\Rewrite.php(470): Zend_Controller_Router_Route->assemble(Array, true, true) #1 C:\xampp\htdocs\fuhrmann\newsletter\library\Zend\View\Helper\Url.php(49): Zend_Controller_Router_Rewrite->assemble(Array, NULL, true, true) #2 [internal function]: Zend_View_Helper_Url->url(Array, NULL, true) #3 C:\xampp\htdocs\fuhrmann\newsletter\library\Zend\View\Abstract.php(350): call_user_func_array(Array, Array) #4 C:\xampp\htdocs\fuhrmann\newsletter\application\layouts\scripts\layout.phtml(22): Zend_View_Abstract->__call('url', Array) #5 C:\xampp\htdocs\fuhrmann\newsletter\application\layouts\scripts\layout.phtml(22): Zend_View->url(Array, NULL, true) #6 C:\xampp\htdocs\fuhrmann\newsletter\library\Zend\View.php(108): include('C:\xampp\htdocs...') #7 C:\xampp\htdocs\fu in C:\xampp\htdocs\fuhrmann\newsletter\library\Zend\Controller\Plugin\Broker.php on line 336
Inside my EDIT action I can do a var_dump in all request params to see if the groupId is set, and yes, it is!
array(3) { ["groupId"]=> string(3) "555" ["controller"]=> string(6) "groups" ["action"]=> string(6) "edit" }
I already have searched for a lot of answers here and by the way, I found a question with an answer but no solution for me.
Thanks!
Ok, solved!
What I did was to add a default value (NULL) to the group_id, so in my Bootstrap file I have this now:
$route = new Zend_Controller_Router_Route('/groups/edit/:group_id',array('controller' => 'groups','action' => 'edit', 'group_id' => NULL));
Thanks #philien!
You can try by removing the underscore :
protected function _initRoutes()
{
$router = Zend_Controller_Front::getInstance()->getRouter();
/* Edit Groups */
$route = new Zend_Controller_Router_Route('groups/edit/:groupId',array('controller' => 'groups','action' => 'edit'));
$router->addRoute('group_edit', $route);
return $router;
}
And after :
<?=$group->getName()?>
Underscore are bad to use in this case, I choose to put names in CamelCased.

Database Connection in Zend Framework

I am new to ZF. I have coded my application.ini here it is:
[development]
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.view.encoding = "utf-8"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
resources.DB.adapter = "pdo_mysql"
resources.DB.params.host = "localhost"
resources.DB.params.username = "root"
resources.DB.params.password = ""
resources.DB.params.dbname = "xyz"
here is my index.php
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()->run();
and here is my bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap{
protected function _initDoctype(){
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype(Zend_View_Helper_Doctype::HTML5);
}
}
now firstly i did my connection like this
$params = array('host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'xyz'
);
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);
$DB->setFetchMode(Zend_Db::FETCH_OBJ);
Zend_Registry::set('DB',$DB);
Later in my queries I used this to retrieve records:
$registry = Zend_Registry::getInstance();
$DB = $registry['DB']; and than my query
Now as I have changed my setting mean including bootstrap and application.ini how to achieve the same as I did? Because in my app everything is like that..
Now I am getting this error.
Notice: Undefined index: DB in
C:\xampp\htdocs\xyz\application\controllers\LoginController.php on line 59
Fatal error: Call to a member function select() on a non-object in C:\xampp\htdocs\xyz\application\controllers\LoginController.php on line 64
Line #59 is
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
Line #64 is
$select = $DB->select()
->from(array('p' => 'phone_service'))
->join(array('u' => 'user_preferences'), 'u.phone_service_id = p.phone_service_id')
->where('u.user_preferences_name = ?', 'is_user_package_active')
->where('p.user_id = ?', $user_id);
Edited
if($result->isValid()){
$data = $authAdapter->getResultRowObject(null,'password');
$auth->getStorage()->write($data);
$this->_redirect('/login/controlpannel');}
Now my query can't find $user_id here
$data = Zend_Auth::getInstance()->getStorage()->read();
$user_id = $data->user_id;
$DB = Zend_Db_Table_Abstract::getDefaultAdapter();
$select = $DB->select()
->from(array('p' => 'phone_service'))
->join(array('u' => 'user_preferences'), 'u.phone_service_id = p.phone_service_id')
->where('u.user_preferences_name = ?', 'is_user_package_active')
->where('p.user_id = ?', $user_id);
That's why I am getting this error
Notice: Trying to get property of non-object in in my .phtml file
By default when using
resources.db.*
in your application.ini a default adapter with these settings will be set up (and by default be used in Zend_Db_Table).
As the adapter is already registered as default adapter in Zend_db_Table_Abstract by default, accessing it is as easy as using:
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
Another way to get it is to fetch it from the bootstrap-instance, which goes something like this (according to Reference Manual):
$front = Zend_Controller_Front::getInstance();
$bootstrapResource = $front->getParam('boostrap')->getPluginResource('db');
$db = $boostrapResource->getDbAdapter();
The Zend_Registry is a object so you should be doing:
$registry = Zend_Registry::getInstance();
$DB = $registry->DB;

Forms not found by autoloader in Zend module?

I'm getting pretty fed up with Zend's autoloader.
I'm trying to load EditPassword from within PasswordController in the module structure as shown below.
application.ini
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.frontController.baseUrl = "/"
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
phpSettings.date.timezone = "Europe/London"
Bootstrap.php:
public function init() {
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
$baseUrl = $config->baseHttp;
define('BASE_URL', $baseUrl);
}
protected function _initAutoload() {
$autoLoader = Zend_Loader_Autoloader::getInstance();
$autoLoader->registerNamespace('App_');
//
$moduleLoader = new Zend_Application_Module_Autoloader(array(
'namespace' => '',
'basePath' => APPLICATION_PATH . 'modules/account',
'resourceTypes' => array(
'form' => array(
'path' => 'forms',
'namespace' => 'Form'))));
$autoLoader->pushAutoloader($moduleLoader);
//
return $autoLoader;
}
I'm loading the form in the controller like this:
$form = new Account_Form_EditPassword();
$this->view->form = $form;
The error itself is:
Fatal error: Class 'Account_Form_EditPassword' not found in
Z:\dat\docs\workspace\metamusic\application\modules\account\controllers\PasswordController.php
on line 7
What am I doing wrong? Everything else in Zend seems to run off fairly sane defaults - do I really have to declare all the paths to forms/models/viewhelpers for each module, given that they're following the default Zend structure, and in the default modules directory?
I would remove all the module autoloading code from the app Bootstrap and then implement an empty module bootstrap in application/modules/account/Bootstrap.php:
class Account_Bootstrap extends Zend_Application_Module_Bootstrap
{
}
Then in application/configs/application.ini, add the following:
resources.modules[] =
The idea here is that Zend_Application_Module_Bootstrap automatically registers a resource autoloader with bunch of common path/namespace mappings, including the one for forms that you are using.
In Bootstrap.php
'basePath' => APPLICATION_PATH . 'modules/acount'
Should be:
'basePath' => APPLICATION_PATH . 'modules/account'
Everything else looks ok
If this a copy/paste from your actual config then you have a typo in 'modules/acount'
'basePath' => APPLICATION_PATH . 'modules/acount',
Depending on your ZF version you don't even need the autoloader in the bootstrap. You can remove it. The following in your ini does the same.
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"

Zend Framework Modules can't find/load Models

For some frustrating reason, I configured some Modules, which seemed to work fine,
However I cannot load a Modules Models. If I move the Models to the Default they load,
but I just can't get the Framework to find them locally..
Example:
My Modules Directory is:
application\modules\books\models\books.php (books is my Model)
class Application_Module_Books_Model_Books extends Zend_Db_Table_Abstract {}
I also tried..
Books_Model_Books, Model_Books, books, Modules_.. you name it I tried it :)
My controller is in the Books Module, and is an Index Controller, and it
can never find the Local Model.
I'm using Application.ini and it is configured this way:
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 1
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
I have a BootStrap in the Modules Directory:
class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{
}
I'm on Zend Framework 1.10, and ideas.. ?
What just fixed it for me was to add the following line to application.ini
resources.modules[]=
Then i added a Bootstrap.php to the module directory ('application\modules\books\')
class Books_Bootstrap extends Zend_Application_Module_Bootstrap {
protected function _initAutoload()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'Books_',
'basePath' => dirname(__FILE__)
));
return $autoloader;
}
}
Move the books model to 'application\modules\books\models\Books.php'
class Books_Model_Books extends Zend_Db_Table_Abstract {...}
Now you should be able to load the model in the IndexController
$model = new Books_Model_Books();
In the application.ini, add a simple line:
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
and in the method _initAutoload() inside the Bootstrap put:
$front = $this->bootstrap("frontController")->frontController;
$modules = $front->getControllerDirectory();
$default = $front->getDefaultModule();
foreach (array_keys($modules) as $module) {
if ($module === $default) {
continue;
}
$moduleloader = new Zend_Application_Module_Autoloader(array(
'namespace' => $module,
'basePath' => $front->getModuleDirectory($module)));
}
make sure the name of models inside each module are like
[name_module]_Model_[name_model]
in you case, like
class Books_Model_Books {
}
and that's all :D
The correct class name would be Books_Model_Books, but the filename of that class would need to be Books.php (note the capital 'B').
You shouldn't have a bootstrap in the modules directory, but you probably do want a bootstrap for each module directory, so you'd need a class:
class Books_Bootstrap extends Zend_Application_Module_Bootstrap
{
}
at: application/modules/books/Bootstrap.php (again note the capital 'B').
Check the section on the module resource autloader at http://framework.zend.com/manual/en/zend.loader.autoloader-resource.html for more info.
1-feel free to delete this cuz you don't need it any more :
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
and place this code inside you Bootstrap.php file [application bootstrap ] not the module bootstrap
public function _initAutoload()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => '' ,
'basePath' => dirname(__FILE__) . '/modules/'));
return $autoloader;
}
getting back to config you need also to add
resources.modules[] = ""
resources.frontController.defaultModule = "admin"
here is my complete config file :
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.defaultModule = "news"
resources.frontController.prefixDefaultModule = 1
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.modules[] = ""
;resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 1
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
autoloaderNamespaces[] = "xxxxxx"
resources.db.adapter = "Mysqli"
resources.db.isdefaulttableadapter = true
resources.db.params.host = "localhost"
resources.db.params.dbname = "xxxxx"
resources.db.params.username = "root"
resources.db.params.password = "root"
resources.db.params.charset = "utf8"
hopefully i didn't miss any thing

Module configuration and layout configuration in zend framework

I got some codes from other articles for configuring module and layout in zend framework. I tried with in my local. i didn't get different layout for default and admin module. Here is my code for configuring module and layout for zend framework.
configs/application.ini
[production]
# Debug output
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
# Include path
includePaths.library = APPLICATION_PATH "/../library"
# Bootstrap
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
admin.bootstrap.path = APPLICATION_PATH "/modules/admin/Bootstrap.php"
admin.bootstrap.class = "admin_Bootstrap"
# Front Controller
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.env = APPLICATION_ENV
# Session
resources.session.name = "ZendSession"
resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.remember_me_seconds = 86400
# Layout
resources.layout.layout = "layout"
resources.layout.layoutPath = APPLICATION_PATH "/layouts"
admin.resources.layout.layout = "admin"
admin.resources.layout.layoutPath = APPLICATION_PATH "/modules/admin/layouts"
# Views
resources.view.encoding = "UTF-8"
resources.view.basePath = APPLICATION_PATH "/views/"
resources.view[] =
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.modules[] =
resources.view[] =
admin.resources.view[] =
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
application/Bootstrap.php
<?php
/**
* Ensure all communications are managed by sessions.
*/
require_once ('Zend/Session.php');
Zend_Session::start();
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initDoctype() {
$this->bootstrap( 'view' );
$view = $this->getResource( 'view' );
$view->navigation = array();
$view->subnavigation = array();
$view->headTitle( 'Module One' );
$view->headLink()->appendStylesheet('/css/clear.css');
$view->headLink()->appendStylesheet('/css/main.css');
$view->headScript()->appendFile('/js/jquery.js');
$view->doctype( 'XHTML1_STRICT' );
//$view->navigation = $this->buildMenu();
}
/*protected function _initAppAutoLoad()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'default',
'basePath' => APPLICATION_PATH
));
return $autoloader;
}*/
protected function _initLayoutHelper()
{
$this->bootstrap('frontController');
$layout = Zend_Controller_Action_HelperBroker::addHelper(
new ModuleLayoutLoader());
}
public function _initControllers()
{
$front = Zend_Controller_Front::getInstance();
$front->addModuleDirectory(APPLICATION_PATH . '/modules/admin/', 'admin');
}
protected function _initAutoLoadModuleAdmin() {
$autoloader = new Zend_Application_module_Autoloader(array(
'namespace' => 'Admin',
'basePath' => APPLICATION_PATH . '/modules/admin'
));
return $autoloader;
}
protected function _initModuleutoload() {
$autoloader = new Zend_Application_Module_Autoloader ( array ('namespace' => '', 'basePath' => APPLICATION_PATH ) );
return $autoloader;
}
}
class ModuleLayoutLoader extends Zend_Controller_Action_Helper_Abstract
// looks up layout by module in application.ini
{
public function preDispatch()
{
$bootstrap = $this->getActionController()
->getInvokeArg('bootstrap');
$config = $bootstrap->getOptions();
echo $module = $this->getRequest()->getModuleName();
/*echo "Configs : <pre>";
print_r($config[$module]);*/
if (isset($config[$module]['resources']['layout']['layout'])) {
$layoutScript = $config[$module]['resources']['layout']['layout'];
$this->getActionController()
->getHelper('layout')
->setLayout($layoutScript);
}
}
}
application/modules/admin/Bootstrap.php
<?php
class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{
/*protected function _initAppAutoload()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'admin',
'basePath' => APPLICATION_PATH . '/modules/admin/'
));
return $autoloader;
}*/
protected function _initDoctype() {
$this->bootstrap( 'view' );
$view = $this->getResource( 'view' );
$view->navigation = array();
$view->subnavigation = array();
$view->headTitle( 'Module One' );
$view->headLink()->appendStylesheet('/css/clear.css');
$view->headLink()->appendStylesheet('/css/main.css');
$view->headScript()->appendFile('/js/jquery.js');
$view->doctype( 'XHTML1_STRICT' );
//$view->navigation = $this->buildMenu();
}
}
Please go through it and let me know any knows how do configure module and layout in right way..
Thanks and regards,
Prasanth P
I use plugin approach with this code I have written:
in main Bootstrap:
protected function _initPlugins()
{
// Access plugin
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new MyApp_Plugin_Module());
}
In plugin directory:
class MyApp_Plugin_Module extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$module = $request->getModuleName();
$layout = Zend_Layout::getMvcInstance();
// check module and automatically set layout
$layoutsDir = $layout->getLayoutPath();
// check if module layout exists else use default
if(file_exists($layoutsDir . DIRECTORY_SEPARATOR . $module . ".phtml")) {
$layout->setLayout($module);
} else {
$layout->setLayout("default");
}
}
Hope it helps.
From your code:
# Layout
resources.layout.layout = "layout"
resources.layout.layoutPath = APPLICATION_PATH "/layouts"
admin.resources.layout.layout = "admin"
admin.resources.layout.layoutPath = APPLICATION_PATH "/modules/admin/layouts"
you are using your_app/modules/admin/layouts/admin.phtml as admin module layout, and I guess it replaced your_app/layouts/layout.phtml. Check a way to switch between modules and try something site.ressources.layout instead of resources.layout.layout. i am a newbie to zend. check out how to setting up you bootstrap at http://www.survivethedeepend.com/
the same problem and solution has been stressed here: http://blog.astrumfutura.com/archives/415-Self-Contained-Reusable-Zend-Framework-Modules-With-Standardised-Configurators.html
In my application I configured this way. It worked perfectly.
protected function _initLayout(){
$layout = explode('/', $_SERVER['REQUEST_URI']);
if(in_array('admin', $layout)){
$layout_dir = 'admin';
}else if(in_array('default', $layout)){
$layout_dir = 'default';
}else{
$layout_dir = 'default';
}
$options = array(
'layout' => 'layout',
'layoutPath' => APPLICATION_PATH."/modules/".$layout_dir."/views/layouts"
);
Zend_Layout::startMvc($options);
}
You need to use a Controller Plugin to achieve that, because the layout is set based on the request entry, and on the bootstrap the application hasn't been dispatched, so you need to use a controller plugin to work on the preDispatch to switch layouts.
I think the easiest way is check the URI_String. Please see below:
I have a module named as "admin".
Under layout folder I have 2 directories. "site" and "admin"
\application\layout\site\layout.phtml and \application\layout\admin\layout.phtml
Add this block of code on Bootstrap.php
It just change the layout directory path.
protected function _initLayout(){
$layout = explode('/', $_SERVER['REQUEST_URI']);
if(in_array('admin', $layout)){
$layout_dir = 'admin';
}else{
$layout_dir = 'site';
}
$options = array(
'layout' => 'layout',
'layoutPath' => APPLICATION_PATH . "/layouts/scripts/".$layout_dir,
);
Zend_Layout::startMvc($options);
}
Your questions answered my question, that's right, I was trying to find out why it did not work in my bootstrap modules, seen in its configuration file that you need to add the line
administrador.resources.view [] =
Valew partner!
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initAutoload() {
$autoloader = Zend_Loader_Autoloader::getInstance();
$moduleLoader = new Zend_Application_Module_Autoloader(
array(
'namespace' => '',
'basePath' => APPLICATION_PATH . '/modules'
)
);
return $moduleLoader;
}
protected function _initViewhelpers()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$view->doctype('XHTML1_STRICT');
$view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
}
protected function _initNavigation()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$config = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml','nav');
$navigation = new Zend_Navigation($config);
$view->navigation($navigation);
}
}
Layout and module in not enabled on a newly zend project (in ZF version 1). It needs to be enabled and you need to make it work.
Layout works for the common header and footer for the working zend project, on the other hand module can be used for the different kind of access i.e module for user, module for admin, module for visitor and so on.
For a quick reference you can find a complete explanation with a complete project to get the basic idea from here, on my site. . http://www.getallthing.com/how-to-use-layout-and-module-in-zend-framework/
Good luck and cheers!
$options = array(
'layout' => 'layout',
'layoutPath' => APPLICATION_PATH."/modules/".$layout_dir."/views/layouts"
);
Zend_Layout::startMvc($options);
Tried a few other solutions from SOF and this one worked great. Just needed to point the layoutPath to the folder of the actual layouts