【问题标题】:kohana: Remove need for default controller routekohana:消除对默认控制器路由的需求
【发布时间】:2012-04-04 08:43:00
【问题描述】:

我有一条路线:

((?<directory>\w+)/?)?((?<controller>\w+)/?)?((?<action>\w+)/?)?((?<id>\d+))?

它工作正常,但它导致我的系统必须为子路由的所有路由包含默认控制器(索引)。例如,如果我的页面 URI 是 /blog/post(其中 blog 是目录,而 post 是操作),我的实际 URI 必须是 blog/index/post - 我希望能够退回到仅使用 @改为 987654324@。

所以,我希望它被路由到:

directory = blog
controller = index
action = post

当第二个参数实际上是一个控制器时,这显然会导致问题。例如directory/controller/action 会被错误地路由。

有没有路由方法检测三个字参数,后面可能跟一个数字参数,可以做我需要的吗?

澄清:

  • param/param/param(?/id) 将是:directory/controller/action(/id)
  • param/param(?/id) 将是:directory/default_controller/action(/id)

【问题讨论】:

    标签: php routing kohana


    【解决方案1】:

    我实际上认为您想将 blog/index/post 别名为 blog/post;将其作为路线插入您拥有的“全能”路线之前; “一只大鞋适合所有人”的方法并不总是最好的。特别是,如果你只有 1 个这样的特殊用例。

    编辑:

    “kohana 的路由系统”令人生畏;无法理解他们试图在那里生下的大象......这里有一些其他建议:

    1. 将此问题提交给制造商;这绝对是一个常见问题解答问题
    2. 搞乱正则表达式模式。这是一个可能有用的 sn-p(我将它放在 PHP 测试用例中,但您可以轻松地将其解耦)

      public function testRoutePatterns(){
          $data = array(
          array(
              //most specific: word/word/word/id
              '~^(?P<directory>\w+)/(?P<controller>\w+)/(?P<action>\w+)/(?P<id>.*)$~i', 
              'myModule/blog/post/some-id',
              array('directory'=>'myModule', 'controller'=>'blog', 'action'=>'post', 'id'=>'some-id'), 
              true
          ),
          array(
              //less specific: word/word/id
              '~^(?P<directory>\w+)/(?P<action>\w+)/(?P<id>.*)$~i', 
              'blog/post/some-id',
              array('directory'=>'blog', 'action'=>'post'), //need to inject "index" controller via "defaults()" here i guess
              true
          ),
          );
      foreach ($data as $d) {
          $matches = array();
          list($pattern, $subject, $expected, $bool) = $d;
          $actual = (bool) preg_match($pattern, $subject, $matches);
          $this->assertEquals($bool, $actual); //assert matching
          $this->assertEquals(array(), array_diff($expected, $matches)); //$expected contained in $matches
       }
      }
      

    【讨论】:

    • 如果是一个案例就好了,但我想要一个通用的解决方案
    • 我认为如果你只创建一条处理所有事情的路线,你就会违背 Kohana 的建议。您确实需要使用多条路线并组织它们以最好地满足您的要求。有一些devtools 可以帮助您根据您的网址确定您正在访问的路线。我认为 Grigorash Vasilij 给出了最好的答案。
    【解决方案2】:

    this answer 中所述,如果您有这样的路线:

    Route::set('route_name', 'directory/controller/action')
        ->defaults(array(
            'directory'  => 'biz',
            'controller' => 'foo',
            'action'     => 'bar',
        ));
    

    你应该有这样的目录结构:

    /application/classes/controller/biz/foo.php
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多