【问题标题】:Zend Framework 2 - custom router (from mysql)Zend Framework 2 - 自定义路由器(来自 mysql)
【发布时间】:2013-06-02 18:12:56
【问题描述】:

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

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

我想在路由器中包含这些 url。

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

提前致谢。

后期编辑:

我想从这个表中路由每个 url。

示例:

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

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

【问题讨论】:

  • 如果您想路由任何类型的 url,请添加一列“模块”。你有什么问题 ?怎么做?
  • @RemiThomas 刚刚编辑了表格(我在模块中更改了控制器)。
  • 不,我会说 url|module|controller|action|param
  • @RemiThomas 好的。不是sql的问题(只是更新了表)。我在路由器中的部分实现有问题。

标签: php zend-framework2 zend-router


【解决方案1】:

执行此操作的一种方法是将事件(优先级 > 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 之前将您的自定义路由添加到路由器。

【讨论】:

  • 感谢您的回复。我有个问题。如果我会有 10k 个网址?
  • 使用 10k 个 URL,您可能希望以不同的方式做事。与其为每个 URL 添加一个文字路由,不如考虑通过实现 RouteInterface 创建自己的 Route 类型。
  • 你能给我一个例子吗?我是 zend 框架 2 的新手。谢谢!
  • 如果一个路由有子路由,我们如何实现呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-05
  • 2011-05-12
相关资源
最近更新 更多