Zend Layout - A "Smart" layout selector - zend-framework

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.

Related

Hide and show navigator menu items, buttons and anchors using ACL

I am using ACL to grant resources to roles in the system, the allowed actions is excuted and denied actions are routed to custom page, I want to show and hide menu elements at run time using resources at ACL, and also I want to show and hide anchors, buttons in views.
I make a helper class
class Zend_View_Helper_Permission extends Zend_View_Helper_Abstract
{
private $_acl;
public function hasAccess($role, $action, $controller)
{
if (!$this->_acl) {
$this->_acl = Zend_Registry::get("Acl");
}
return $this->_acl->isAllowed($role, $controller, $action);
}
}
I define the view helper in config.ini file like this
resources.view.helperPath.Zend_View_Helper = APPLICATION_PATH "/modules/privileges/views/helpers"
how can I use this helper to make views created at run time?
Your method name should match class name hence it should be permission instead of hasAccess.
I myself use a global method show() instead of using view helper
function show($action = null)
{
$request = Zend_Controller_Front::getInstance()->getRequest();
$action = $action === null ? $request->getActionName() : $action;
$module = $request->getModuleName();
$controller = $request->getControllerName();
if(!Zend_Registry::isRegistered('acl')) throw new Exception('Show function can only be called inside view after preDispatch');
$acl = Zend_Registry::get('acl');
$resource = $module . '#' . $controller;
return $acl->isAllowed(Zend_Auth::getInstance()->getIdentity(),$resource,$action);
}
To keep it simple it takes controller , module name from request object .
To hide edit action link in list action view simply doo
list.phtml code as follow
<h2>Listing page Only superadmin can see edit link</h2>
<?php if(show('edit')): ?>
Edit
<?php endif;?>
Update
The global function show was defined inside library/Util.php which was loaded inside
public/index.php
require_once 'Zend/Application.php';
require_once 'Util.php';

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 and Ext-Js4, file and folder structure

I am trying to use Zend Frame work and Ext-Js4 together.
But I don't know how to setup file and folder structure correctly.
I setup like this,
And in application/controllers/IndexController.php
$this->view->headScript()->appendFile('/js/ext-4.0.7/ext-all.js','text/javascript');
$this->view->headScript()->appendFile('/js/app.js','text/javascript');
$this->view->headLink()->appendStylesheet('/js/ext-4.0.7/resources/css/ext-all.css');
Is it right structure? anyone has a better idea?
Thank you.
If you're using Ext-Js4 in your entire application, a better idea would be to add this in your bootstap, so that you don't have to include your javascript paths in every controllers.
protected function _initView()
{
$view = new Zend_View();
$view->headScript()->appendFile('/js/ext-4.0.7/ext-all.js','text/javascript');
$view->headScript()->appendFile('/js/app.js','text/javascript');
$view->headLink()->appendStylesheet('/js/ext-4.0.7/resources/css/ext-all.css');
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($view);
return $view;
}
I tend to use a layout for things like this:
function _initViewHelpers()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$view->doctype('HTML4_STRICT');
$view->headMeta()->appendHttpEquiv('Content-type', 'text/html;charset=utf-8')
->appendName('description', 'My App');
$view->headTitle()->setSeparator(' - ')
->headTitle('My App');
}
Then in my application.ini file I include:
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH "/layouts
There are always more ways to skin the proverbial cat!

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');

Zend: Where/how can I register custom view helpers?

In my layout.phtml file I have :
<?php echo $this->Test(); ?>
I have created a Test view helper at application/views/helpers/Test.php
<?php
class My_View_Helper_Test extends Zend_View_Helper_Abstract {
public function Test() {
return 'test';
}
}
And my config file # configs/application.ini:
resources.view[] = ''
resources.view.helperPath = APPLICATION_PATH "/views/helpers"
Error I get:
Zend_Loader_PluginLoader_Exception:
Plugin by name 'Test' was not found in
the registry; used paths:
Zend_View_Helper_:
Zend/View/Helper/:./views/helpers/ in
/usr/share/php/Zend/Loader/PluginLoader.php
on line 406
On a similar note I can't register my admin view helper either..
resources.view.helperPath.Admin_View_Helper = APPLICATION_PATH "/modules/admin/views/helpers"
My modules/admin/views/helpers/AdminPanel.php:
<?php
class My_View_Helper_AdminPanel extends Zend_View_Helper_Abstract {
public function AdminPanel() { return 'test'; }
}
Do I have no choice but to do this in the Bootstrap with addHelperPath? If so could someone demonstrate how I would using my paths?
Using application.ini is probably the best way to define these. I put all my view helpers inside my library folder:
includePaths.library = APPLICATION_PATH "/../library"
autoloadernamespaces.0 = "SNTrack_"
; -- Note, these are the only resources.view lines I have...
resources.view.doctype = "XHTML1_STRICT"
resources.view.helperPath.SNTrack_View_Helper = APPLICATION_PATH "/../library/SNTrack/View/Helper"
Directory structure:
/
application/
library/
SNTrack/
View/
Helper/
Test.php
View:
$this->test('test')
SNTrack/View/Helper/Test.php:
class SNTrack_View_Helper_Test extends Zend_View_Helper_Abstract {
public function test($args) { return $args; }
}
in my bootstrap:
$view = new Zend_View();
$view->addHelperPath(DE_Config::get('DE_appDir').DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'DE'.DIRECTORY_SEPARATOR.'View'.DIRECTORY_SEPARATOR.'Helper'.DIRECTORY_SEPARATOR, 'DE_View_Helper');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
I just had this exact problem, and realised it was due to a problem in my bootstrap: I was defining and using a new Zend_View object in one of my _init functions, which I think was overwriting all my other view settings from both my bootstrap and my application.ini file (including my resources.view.helperPath definition). The offending code had been blindly copied from here, and placed into an _initJQuery() function in my bootstrap, which looked like this:
protected function _initJQuery() {
$view = new Zend_View();
$view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
}
The solution was to replace the first line ($view = new Zend_View()) with this:
$this->bootstrap('view');
$view = $this->getResource('view');
Another thing to bare in mind, regarding your line:
resources.view.helperPath = APPLICATION_PATH "/views/helpers"
Note that this only registers the path, and not the class prefix, so this will only work if the helper classes have the default Zend class prefix of Zend_View_Helper i.e. Zend_View_Helper_Test. If you want the class to be My_View_Helper_Test, then you need to do this:
resources.view.helperPath.My_View_Helper = APPLICATION_PATH "/views/helpers"