【问题标题】:Routing in CakePHP to vanity urls在 CakePHP 中路由到虚 url
【发布时间】:2012-10-19 02:30:27
【问题描述】:

我想知道是否有一种简单且最佳实践的方法可以在 CakePHP(routes.php 文件)中创建路由以将用户 ID 映射到虚 url?

我的路线页面中有以下测试代码(这样做很糟糕):

$users = array
(
    1 => 'firstname-lastname',
    2 => 'firstname2-lastname2'
);   

//profiles
foreach($users as $k => $v)
{
    // LESSONS (Profiles)
    Router::connect('/:user', array('controller' => 'teachers', 'action' => 'contentProfile', $k),
        array('user' => '(?i:'.$v.')'));
}

上面的代码使用 conProfile 作为动作路由我的教师控制器:

mydomain.com/teachers/contentProfile/1
to
mydomain.com/firstname-lastname

我可以从路由页面连接到数据库吗?就性能而言,这不是一个好主意吗?让我知道最好的方法是什么。

【问题讨论】:

    标签: php cakephp routing routes cakephp-2.1


    【解决方案1】:

    您可以创建一个自定义路由类,该类将在数据库中查找传递的 url 并将它们转换为正确的用户 ID。设置较长的缓存时间应该可以减轻命中数据库的任何性能影响。

    The book documentation虽然有点单薄,但基本结构是这样的:

    class TeachersRoute extends CakeRoute {
    
      /**
       * Modify incoming parameters so that controller receives the correct data
       */
      function parse($url) {
        $params = parent::parse($url);
    
        // Add / modify parameter information
    
        // The teacher id should be sent as the first value in the $params['pass'] array
    
        return $params;
        // Or return false if lookup failed
      }
    
      /**
       * Modify parameters so calls like HtmlHelper::url() output the correct value
       */
      function match($url) {
        // modify parameters
    
        // add $url['slug'] if only id provided
    
        return parent::match($url);
      }
    

    然后在你的路线中:

    Router::connect(
      '/:slug', 
      array(
        'controller' => 'teachers', 
        'action' => 'contentProfile'
      ), 
      array(
        'slug' => '[a-zA-Z0-9_-]+'
        'routeClass' => 'TeachersRoute',
      )
    );
    

    【讨论】:

    • 谢谢,这就是我想要的。是的,这本书也有点薄。
    • Mark Story 也有一篇关于自定义路由类的旧文章:mark-story.com/posts/view/using-custom-route-classes-in-cakephp
    • 是的,当我也看到你的答案时,我正在阅读那个。再次感谢。
    • 你是放在 App/Lib/MyRouteClass.php 还是别的地方?如何在 Lib 中创建路由文件夹?
    • 我如何制作 Html 链接(例如 HtmlHelper->url 使它们成为 mydomain.com/first-last/media ,例如 /teachers/contentMedia/X
    猜你喜欢
    • 2011-07-23
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2014-01-01
    • 1970-01-01
    • 2014-09-25
    相关资源
    最近更新 更多