一种方法是将事件(优先级> 0,这很重要!)附加到应用程序的“路由”事件。这个正优先级将导致处理程序在路由匹配发生之前执行,这意味着您有机会添加自己的路由。
类似于以下内容。请记住,这没有在任何地方进行测试,因此您可能需要清理一些东西。
<?php
namespace MyApplication;
use \Zend\Mvc\MvcEvent;
use \Zend\Mvc\Router\Http\Literal;
class Module {
public function onBootstrap(MvcEvent $e){
// get the event manager.
$em = $e->getApplication()->getEventManager();
$em->attach(
// the event to attach to
MvcEvent::EVENT_ROUTE,
// any callable works here.
array($this, 'makeSeoRoutes'),
// The priority. Must be a positive integer to make
// sure that the handler is triggered *before* the application
// tries to match a route.
100
);
}
public function makeSeoRoutes(MvcEvent $e){
// get the router
$router = $e->getRouter();
// pull your routing data from your database,
// implementation is left up to you. I highly
// recommend you cache the route data, naturally.
$routeData = $this->getRouteDataFromDatabase();
foreach($routeData as $rd){
// create each route.
$route = Literal::factory(array(
'route' => $rd['route'],
'defaults' => array(
'module' => $rd['module'],
'controller' => $rd['controller'],
'action' => $rd['action']
)
));
// add it to the router
$router->addRoute($route);
}
}
}
这应该确保在应用程序尝试查找 routeMatch 之前将您的自定义路由添加到路由器。