ZF2 -自定义和动态URL


ZF2 - custom and dynamic URL

我想从自定义URL动态路由到特定的操作和控制器。例如,我有以下表格:

controller | action | alias
=============================
home       | index  | myalias

我想在路由之前附加一些函数(我不确定),这将检查URL,如果它将是

my-site.com/myalias
那么

应该使用controller home和action index而不需要重定向。只打开那个动作和控制器,不改变URL。有可能实现吗?

到目前为止,我有这样的东西:

public function customRoutes(MvcEvent $e)
{
    $dbAdapter = $e->getApplication()->getServiceManager()->get('Zend'Db'Adapter'Adapter');
    // pobierz routingi
    $rowset = $dbAdapter->query("SELECT * FROM public.seo WHERE ghost IS NOT TRUE AND alias IS NOT NULL")->execute();
    $routeName = 'custom_route_';
    $i = 1;
    if (sizeof($rowset) > 0) {
        foreach ($rowset as $item) {
            if (strpos($item['alias'], '/') !== 0) {
                $alias = '/' . $item['alias'];
            } else {
                $alias = $item['alias'];
            }

            $route = 'Zend'Mvc'Router'Http'Segment::factory(array(
                'route' => $alias . '[/:id][/:page]',
                'constraints' => array(
                    'id'     => '[0-9a-zA-Z]+',
                    'page' => 'page'-[a-zA-Z0-9_-]*',
                ),
                'defaults' => array(
                    'controller' => $item['controller'],
                    'action'     => $item['action'],
                ),
            ));

            $e->getRouter()->addRoute($routeName . $i, $route);
            $this->custom_routes[] = $routeName . $i;
            $i++;
        }
    }
}

现在我需要改变url helper从我的自定义路由创建链接。例如:

$this->url('home');

结果链接应该是(因为别名在数据库中):

/myalias
除了:

/home

我不知道ZF2,但我已经在ZF1中多次这样做了…你只需要用硬编码的控制器和动作来设置自定义路由。这是我在ZF2文档中发现的内容(针对您的情况进行了修改):

// In bulk:
$router->addRoutes(array(
    // providing configuration to allow lazy-loading routes:
    'bar' => array(
        'type' => 'literal',
        'options' => array(
            'route' => '/myalias',
            'defaults' => array(
                'controller' => 'home',
                'action'     => 'index',
            ),
        ),
    ),
));

ZF2 DocRef: http://framework.zend.com/manual/2.0/en/modules/zend.mvc.routing.html