0

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

例如:这是 URL: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 中的 controllers['invokables'] 设置中。

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

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

4

1 回答 1

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__,
                ),
            ),
        );
    }
}
于 2013-09-22T11:59:27.377 回答