【问题标题】:Need to setup cleaner links - currently links too long - Zend framework需要设置更清晰的链接 - 当前链接太长 - Zend 框架
【发布时间】:2010-02-24 18:33:27
【问题描述】:

我正在为我的项目使用 zend 框架 - 我尝试使用干净的链接进行设置 - 但是我注意到我的链接似乎变得非常长,并且想知道此时是否会有合并一个结构的方法,我可以在其中使用较小的链接。

这是一个例子,我的网站有一个目录控制器,它有一个带有 id 参数的人员操作 - 因此查看具有特定 id 的人员的链接如下所示:

www.mywebsite.com/directory/person/id/1809

看起来没问题,但我现在正在努力使链接更具可读性和搜索引擎友好 - 我想要类似的东西 - 假设用户 ID 1809 被命名为 John Smith:

www.mywebsite.com/directory/person/John-Smith-1809

像下面这样基本的东西会更好:

www.mywebsite.com/John-Smith-1809

虽然我不知道如何在不提及控制器或动作的情况下管理它......任何想法都会真正帮助......

【问题讨论】:

    标签: php zend-framework url-rewriting clean-urls


    【解决方案1】:

    看看ZF Manual on how to use Routes。

    基本上,你需要这样的东西才能让它工作:

    $route = new Zend_Controller_Router_Route_Regex(
        '(.+)-(\d+)',
        array(
            'controller' => 'directory',
            'action'     => 'person'
        ),
        array(
            1 => 'name',
            2 => 'id'
        ),
        '%s-%d'
    );
    $router->addRoute('directoryPerson', $route);
    

    注意:不要指望它开箱即用。您可能必须对其进行修改。不过应该让你进入正确的方向。

    【讨论】:

      【解决方案2】:

      就像之前的回答说你可以使用正则表达式路由,但对于初学者来说,使用看起来像这样的“常规”路由可能会更容易:

      http://yoursite.com/1234/John-Smith/

      在您的引导程序中,您会这样做:

      $frontController = Zend_Controller_Front::getInstance();
      $router = $frontController->getRouter();
      
      $router->addRoute('user', new Zend_Controller_Router_Route(
          ':user-id/:user-name/',
          array(
              'module' => 'user',
              'controller' => 'user',
              'action' => 'read'
          )
      ));
      

      这会向路由器添加一个名为“user”的路由,其格式为 /user-id/user-name,因此是 /1234/John-Smith/。它将在用户模块中查找用户控制器,然后执行读取操作。如果您愿意,当然可以将其更改为另一个模块/控制器/操作。

      然后你会在 User 模块中拥有那个 User_UserController,它有一个 readAction();在该操作中,您可以通过以下方式获取 id:

      $userId = $this->_getParam('user-id');
      

      类似,如果你需要它,你可以检索名称。

      $userName = $this->_getParam('user-name');
      

      在视图脚本中,您可以使用以下命令生成该路由的 url:

      <?php echo $this->url(array('user-id' => 1234, 'user-name' => 'John Smith'), 'user', true); ?>
      

      注意“用户”参数,它告诉路由器使用我们之前定义的“用户”路由。

      【讨论】:

        【解决方案3】:

        您可以使用 apache 模块 mod_rewrite 来重写您的 URL

        http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

        <IfModule mod_rewrite.c>
        
          RewriteEngine On
        
          RewriteCond ###blah blah blah###
          RewriteRule ###blah blah blah###
        
        </IfModule>
        

        【讨论】:

        • 好酷。您可以使用 mod_reqrite 通过将短 URL 映射到当前版本来缩短 URL。
        猜你喜欢
        • 2013-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-27
        • 2022-01-07
        • 1970-01-01
        相关资源
        最近更新 更多