7

我对 Zend Framework 2 有疑问:

我有库/系统和库/Zend。该系统是我的自定义库,我想对其进行配置(路由、模块等,并将用户重定向到正确的模块、控制器和/或操作)。

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

4

1 回答 1

9

正如上面评论中所说:注册到引导事件并在那里添加新路由:

<?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 兼容
于 2012-01-02T16:27:37.627 回答