Skip to content

Instantly share code, notes, and snippets.

@EvanDotPro EvanDotPro/module-specific-layouts.md Secret
Last active Dec 17, 2016

Embed
What would you like to do?

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

This comment has been minimized.

Copy link

commented Dec 17, 2016

Thanks it's really helpfull 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.