【问题标题】:String replacement in CakePHP routesCakePHP 路由中的字符串替换
【发布时间】:2011-01-09 18:48:30
【问题描述】:

在我的应用程序中,我有许多具有相同前缀的控制器。例如,假设它们是:

my_posts
my_users
my_letters

为这些生成的 URL 显然是:

/my_posts/view/1
/my_users/add
/my_letters/whatever

我想设置一些自定义路由,以便我可以使用这样的 URL:

/my/posts/view/1
/my/users/add
/my/letters/whatever

所以基本上,如果 URL 以 /my/ 开头,那么要传递给的控制器应该是 my_{whatever_comes_next}

我一直在看the documentation,但还是想不通。

【问题讨论】:

    标签: php model-view-controller cakephp routing url-rewriting


    【解决方案1】:
    Router::connect(
        '/my/posts/:action/*',
        array(
            'controller'=>'my_posts',
            'action'=>'index'
        )
    );
    Router::connect(
        '/my/users/:action/*',
        array(
            'controller'=>'my_users',
            'action'=>'index'
        )
    );
    [..]
    

    同意,这不是很舒服,但它应该工作..

    【讨论】:

    • 这就是我最终的结果。
    【解决方案2】:

    不确定是否可行,但为什么不使用中间路由器?

    Router::connect (
        '/my/*', 
        array (
            'controller' => 'my_router', 
            'action' => 'route',
        )
    );
    
    class MyRouterController extends AppController {
        ... 
        function route ()
        {
            $args = func_get_args ();
            $controller = array_shift ($args);
            $this->requestAction (
                'my_'.$controller.'/'.implode('/', $args), 
                array ('return' => true)
            );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 2013-11-30
      • 2019-09-04
      • 2019-10-17
      • 2012-04-26
      • 1970-01-01
      • 2022-10-15
      相关资源
      最近更新 更多