ZF2:依赖注入、MVC、配置和引导


ZF2: Dependency Injection, MVC, Configurations and Bootstrap

我有一个关于Zend Framework 2的问题:

library/System和library/Zend。系统是我的自定义库,我想要配置应用程序(路由、模块等,并将用户重定向到正确的模块、控制器和/或操作)。

我不想在每个application/modules/ModuleName/Module.php文件中这样做。因此,我的库/系统可以做所有与应用程序配置相关的事情。

如上所述:注册到bootstrap-event,并在那里添加新的路由:

<?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');返回Zend'Mvc'Application的一个实例。看一下那里,看看你可以得到哪些额外的部分。bootstrap事件在实际调度发生之前触发。

注意ZendFramework 1的路由并不总是与ZendFramework 2的路由兼容。

更新注释

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

更新到新问题

<?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
    }
}

这只发生在一个 zf2模块(命名为Application,也可以是唯一的一个)中。这个不符合你的需求?你可以:

  • 扩展自定义模块自动加载器
  • 扩展Zend'Mvc'Application为您自己的逻辑
  • 使你的代码zf2兼容