Krishna Shasankar
Krishna Shasankar

Reputation: 144

Ideal Location to Set default layout for Zend Framework 2 Controller?

I want to set a different layout for a new Controller, please provide your suggestion on an ideal location to set it across the controller? Right now I am using $this->layout() in each and ever action. In ZF1 there used to be preDispatch , not sure how it is implemented in ZF2.

Upvotes: 1

Views: 1754

Answers (1)

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

Every controller triggers an event dispatch when the controller action is called. This event is encapsuled within an EventManager object which contains some identifiers. This makes it possible for a SharedEventManager to listen to a specific event within an EventManager with a specific identifier.

Now every controller (eg the MyModule\Controller\FooController) has two known identifiers:

  1. The name of the class (MyModule\Controller\FooController)
  2. The top level namespace of the class (MyModule)

The Module.php class for your MyModule is the best place to put this logic. When the application bootstraps, you attach a listener for this module (that is, the namespace of the Module.php class!), for the dispatch event. This makes sure the function is called when your controller's actions are called, but the listener does not execute when another controller is dispatched.

namespace MyModule;

use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap($e)
    {
        $app = $e->getApplication();
        $em  = $app->getEventManager(); // Specific event manager from App
        $sem = $em->getSharedManager(); // The shared event manager

        $sem->attach(__NAMESPACE__, MvcEvent::EVENT_DISPATCH, function($e) {
            $controller = $e->getTarget(); // The controller which is dispatched
            $controller->layout('layout/my-module-layout');
        });
    }
}

This method (how to do stuff with controllers inside a specific module) is also explained at a blog post of mine. Because module specific layouts become quite a common thing in Zend Framework 2, Evan Coury has made a module for this. It is called EdpModuleLayout and it's fairly easy when you installed the module.

You provide an array of MyModule => layout/template in a configuration and the module handles the rest.

Upvotes: 3

Related Questions