ZF2动态路由

时间:2013-09-22 10:24:02

标签: php controller routing zend-framework2

我在ZF2中遇到路由问题。我想为我正在制作的软件制作动态路由。

例如: 这是网址:http://localhost:8080/application/index.json/ 这是我的module.config(路由器部分):

'router' => array(
        'routes' => array(
            'home' => array(
                'type' => 'Zend\Mvc\Router\Http\Segment',
                'options' => array(
                    'route'    => '/',
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                    ),
                ),
            ),
            'restful' => array(
                'type'    => 'Zend\Mvc\Router\Http\Segment',
                'options' => array(
                    'route'       => '/:module/[:controller[/:action][.:formatter][/:id]]',
                    'constraints' => array(

                        'module' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'formatter'  => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'         => '[a-zA-Z0-9_-]*'
                    ),


                ),
            ), 

      ), 
 ), 

一切正常,但是当我创建新的控制器时,必须将它添加到module.config中的控制器['invokables']设置。

'controllers' => array(
    'invokables' => array(
        'index' => 'Application\Controller\IndexController',
        'cloud' => 'Application\Controller\CloudController',
    ),
),

所以问题是,如何自动化控制器['invokables']来动态处理请求,而不需要描述其中的每个控制器。

1 个答案:

答案 0 :(得分:1)

快而又脏,但你明白了。

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();

        $eventManager->attach (MvcEvent::EVENT_ROUTE, function (MvcEvent $e) {
            $controller_loader = $e->getApplication ()->getServiceManager ()->get ('ControllerLoader');

            $controller = $e->getRouteMatch ()->getParam ('controller');
            $controller_class = '\Application\Controller\\'.ucfirst ($controller).'Controller';

            // Add service locator to the controller
            $controller_object = new $controller_class;
            $controller_object->setServiceLocator ($e->getApplication ()->getServiceManager ());
            // ------------------------------------
            $controller_loader->setService ($controller, $controller_object);
        });
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
}