Skip to content

Instantly share code, notes, and snippets.

@EvanDotPro
Last active December 17, 2016 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvanDotPro/778456194d0ff2c9ff5d to your computer and use it in GitHub Desktop.
Save EvanDotPro/778456194d0ff2c9ff5d to your computer and use it in GitHub Desktop.

First, I should point out that the title of this post is a bit of an intentional misnomer. There's really no such thing as "module-specific" anything in ZF2, so what we're really talking about is the topmost namespace of the controller being dispatched. So in the case of MyModule\Controller\SomeController, the topmost namespace would be MyModule. In most cases, this will be the name of a given module.

UPDATE: The information in this post is still correct and applicable, but I've made a very simple module called EdpModuleLayouts to make it even easier.

Here's how you can easily switch the layout (or perform any other arbitrary logic) for a specific module in Zend Framework 2.0 (as of d0b1dbc92):

<?php
namespace MyModule;

use Zend\ModuleManager\ModuleManager;

class Module
{
    public function init(ModuleManager $moduleManager)
    {
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
            // This event will only be fired when an ActionController under the MyModule namespace is dispatched.
            $controller = $e->getTarget();
            $controller->layout('layout/alternativelayout');
        }, 100);
    }
}

This event listener will only be triggered if an ActionController under the MyModule namespace is dispatched, so you do not need to perform any additional logic to check which "module" or namespace the controller being dispatched is under.

Keep in mind, as of writing this, ZF2 is still in beta. There are plans to add a convenience layer to the framework before the GA release which will likely make common tasks like this much simpler.

See also: Rob Allen's post on module specific bootstrapping in ZF2

@csskevin
Copy link

Thanks it's really helpfull 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment