Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2: Dependency Injection, MVC, Configurations and Bootstrap

I have a questiom regarding the Zend Framework 2:

I have library/System and library/Zend. the system is my custom library, which I want to configure de aplication (routes, modules, etc., and redirect user to correct module, controller and/or action).

I don't want to do this inside each application/modules/ModuleName/Module.php file. So, my library/System can do everything related to application configuration.

like image 619
Gabriel Santos Avatar asked Dec 31 '11 19:12

Gabriel Santos


1 Answers

As said in the comments above: register to the bootstrap-event and add new routes there:

<?php

namespace Application;

use Zend\Module\Manager,
    Zend\EventManager\StaticEventManager;

class Module
{
    public function init(Manager $moduleManager)
    {
        $events = StaticEventManager::getInstance();
        $events->attach('bootstrap', 'bootstrap', array($this, 'initCustom'), 100);
    }

    public function initCustom($e)
    {
        $app = $e->getParam('application');
        $r = \Zend\Mvc\Router\Http\Segment::factory(array(
                'route'    => '/test',
                'defaults' => array(
                    'controller' => 'test'
                )
            )
        );
        $app->getRouter()->addRoute('test',$r);
    }
}

$app = $e->getParam('application'); does return an instance of Zend\Mvc\Application. Have a look there to see which additional parts you can get there. The bootstrap event is fired before the actual dispatching does happen.

Note that the ZendFramework 1 routes are not always compatible to the ZendFramework 2 ones.

Update to comments

public function initCustom($e)
{
    $app = $e->getParam('application');
    // Init a new router object and add your own routes only
    $app->setRouter($newRouter);
}

Update to new question

<?php

namespace Application;

use Zend\Module\Manager,
    Zend\EventManager\StaticEventManager;

class Module
{
    public function init(Manager $moduleManager)
    {
        $events = StaticEventManager::getInstance();
        $events->attach('bootstrap', 'bootstrap', array($this, 'initCustom'), 100);
    }

    public function initCustom($e)
    {
        $zendApplication = $e->getParam('application');
        $customApplication = new System\Application();
        $customApplication->initRoutes($zendApplication->getRouter());
        // ... other init stuff of your custom application
    }
}

This only happens in one zf2 module (named Application which can be the only one as well). This doesn't fit your needs? You could:

  • extend a custom module autoloader
  • extend Zend\Mvc\Application for your own logic
  • make your code zf2-compatible
like image 131
Fge Avatar answered Oct 15 '22 03:10

Fge