Zend框架2 -自定义路由器(从mysql)


Zend Framework 2 - custom router (from mysql)

我有一个关于zend框架2路由器的问题。我有一个表"seourl"在mysql像这样:

url             module          controller         action          param
test123         catalog         product            view            5       
abc123          catalog         product            view            6
other           catalog         category           view            10

我想把这些url包含在router.

在url字段中我可以有这样的url: others/product/(我想从这个表中路由任何类型的url)

提前感谢。

后来编辑:

我想路由该表中的每个url。

例子:

example.com/test123将加载模块catalog/控制器product/动作view/参数5

example.com/other将加载模块catalog/控制器category/动作view/参数10

一种方法是给应用程序的'route'事件附加一个事件(优先级> 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之前,你的自定义路由已经被添加到路由器中。