【问题标题】:cakephp routing without id?没有id的cakephp路由?
【发布时间】:2009-11-12 01:01:54
【问题描述】:

有没有什么方法可以在不包含 ID 的情况下在 cake 中路由 url?

所以我只想要 www.mydomain.com/article-name 而不是 www.mydomain.com/id/article-name

我一直在关注这个。 http://book.cakephp.org/view/543/Passing-parameters-to-action

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    当然。唯一的要求是 URL 中有足够的唯一信息来确定您想要的文章。如果/article-name 在您的数据库中是唯一的,您可以使用它来查找您想要的特定记录。

    在 config/routes.php 中:

    // ... configure all normal routes first ...
    
    Router::connect('/*', array('controller' => 'articles', 'action' => 'view'));
    

    在控制器/articles_controller.php 中:

    function view ($article_name) {
        $article = $this->Article->find('first', array(
            'conditions' => array('Article.name' => $article_name)
        ));
        ...
    }
    

    请注意不要将您的产品命名为可以合法出现在 URL 中的任何名称,以免发生冲突。 URL http://example.com/pages 是指向产品“页面”还是指向array('controller' => 'pages', 'action' => 'index')?为此,您还需要在routes.php 中定义您的路由,以允许首先访问所有控制器,并且只有未定义的其余部分通过管道传输到您的ArticlesController。查看third parameter of Routes::connect,它允许您指定可用于此目的的RegEx 过滤器。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      // In routes.php
      $rewrites = array();
      $rewrites = am($rewrites, ClassRegistry::init('Article')->rewrites());
      $rewrites = am($rewrites, ClassRegistry::init('AnotherModel')->rewrites());
      $rewrites = am($rewrites, ClassRegistry::init('YetAnother')->rewrites());
      foreach ($rewrites as $rewrite) {
          Router::connect($rewrite[0], $rewrite[1], $rewrite[2]);
      }
      

      使用 deceze 的方法,您只能一网打尽。在此方法中,您可以根据需要定义整个堆栈。

      不过,这种方法有点 hacky,因为您是从配置文件中查询模型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-15
        • 1970-01-01
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        相关资源
        最近更新 更多