我对zend framework 2路由器有疑问。 我在mysql中有一个表“seourl”:
url module controller action param
test123 catalog product view 5
abc123 catalog product view 6
other catalog category view 10
我想在路由器中包含这些网址。
在网址字段中我可以有这样的网址:其他/产品/(我想从此表中路由任何类型的网址)
提前致谢。
稍后编辑:
我想从此表中路由每个网址。
示例:
example.com/test123将加载模块catalog
/ controller product
/ action view
/ param 5
example.com/other将加载模块catalog
/ controller category
/ action view
/ param 10
答案 0 :(得分:4)
执行此操作的一种方法是将事件(优先级> 0,这很重要!)附加到应用程序的“route”事件。这个正优先级将导致在路由匹配发生之前执行处理程序,这意味着您有机会添加自己的路由。
如下所示。请记住,这不会在任何地方进行测试,因此您可能需要清理一些东西。
<?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之前将自定义路由添加到路由器。