如何使用文本而不是ID来路由页面?

时间:2015-05-27 19:42:43

标签: zend-framework zend-framework2 zend-route zend-router

目前,我的Zend应用程序路由使用URL:

example.com/news/12

选择ID为12的新闻在页面上显示 但客户只想使用文字,例如:

example.com/news/man-dies-after-burning-himself

有人知道怎么做?

2 个答案:

答案 0 :(得分:2)

有两种方法。如果没有你的代码,将很难解释,但我会给它一个机会。首先,有一种方法可以解决它是通过使用名为friendlyUrl的属性存储您的新闻(例如)而不是按ID选择新闻,您可以通过friendlyUrl选择它,但是,您必须检查总是那个friendlyUrl没有存储其他新闻。而friendlyUrl应来自新闻标题解析,该功能删除了网址中不允许的所有特殊字符,并用' - '替换空格。另一种方式是StackOverflow的方式,例如,在URL中使用ID和TEXT:

  

How to route pages using text instead of IDs?

如果您检查了该网址,您将首先看到该ID,以及您之后想要呼叫它的friendlyUrl或friendlyName。

答案 1 :(得分:1)

在你的module.config.php

'router' => array(
    'routes' => array(
        'news' => array(
            'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route' => '[/:news][/:url][/]', 
                'constraints' => array(
                    'url' => '[a-zA-Z][a-zA-Z0-9_-]*',
                ),
                'defaults' => array(
                    '__NAMESPACE__' => 'YourModule\Controller',
                    'controller'    => 'News',
                    'action'        => 'index',
                ),
            ),
        ),
    ), 
),

如果您选择使用文本而不是ID,则必须确保该网址是唯一的,否则您的应用程序将切断第一个匹配项。 在您添加的示例中:

url ='man-dies-after-burning-their'

这将涵盖:

  • example.com/news/man-dies-after-burning-himself
  • example.com/news/man-dies-after-burning-himself-2015-07-07
  • example.com/news/man
  • example.com/news/2015-07-07 .....