m939594960
V2EX  ›  PHP

像 laravel 那样的路由分组功能是如何实现的呢?

  •  
  •   m939594960 · May 23, 2015 · 3676 views
    This topic created in 4017 days ago, the information mentioned may be changed or developed.

    `
    DreamRoute::group('/ccc','Auth',function (){
    DreamRoute::get('/fuck(:any)',function (){

    });
           DreamRoute::get('/dream(:any)',function (){
    
           });
    });
    

    `

    就类似这样的路由声明
    /fuck 和 /dream 都是属于 /ccc这个group的
    也就是 /ccc/fuck 还有 /ccc/dream 会匹配到这两条路由中

    问题就是

    DreamRoute::get('/fuck(:any)',function (){
    
    });
    DreamRoute::get('/dream(:any)',function (){
    
    });
    如何获取 /ccc
    

    试过group 放到静态的变量中 初始值为0
    可是这样就不行
    ```
    DreamRoute::group('/admin','Auth',function (){
    DreamRoute::get('/fuck(:any)',function (){

    });
        DreamRoute::get('/cao(:any)',function (){
    
        });
    });
    DreamRoute::get('/fuck(:any)',function (){
    
    });
    DreamRoute::get('/cao(:any)',function (){
    
    });
    
    求教这种路由该如何实现
    
    
      代码如何格式化。。。。 反正我是尽力了 还是没格式化成。。
    
    6 replies    2015-05-25 13:04:43 +08:00
    ywisax
        1
    ywisax  
       May 23, 2015
    研究下lara的route不就行了。
    如果觉得lara实现复杂,可以看下slim的route(slim/Slim/Router.php)。
    m939594960
        2
    m939594960  
    OP
       May 23, 2015
    @ywisax 研究了但没看懂 尴尬。。。。。
    Septembers
        3
    Septembers  
       May 23, 2015
    route简单的说是个有限状态机,group相当于做了个状态转移
    m939594960
        4
    m939594960  
    OP
       May 23, 2015
    @Septembers 没有浅显易懂点的解释么。。。。瞬间就感觉自己啥都不会了,,,
    yangmls
        5
    yangmls  
       May 23, 2015
    这不是很简单嘛,Laravel 的这部分用三句就能解释了

    ```
    //group 的层级,实现多层group嵌套
    $this->groupStack[] = 'group';
    //运行 group 的第二个参数
    call_user_func(xxxx, $this);
    //结束就删掉group的层级
    array_pop($this->groupStack);
    ```

    Router 因为是个 Facade,所以是个单例,所有 Router 代码共享 $this->groupStack 变量,Router::add 的代码会检查当前 $this->groupStack 的层级,prepend 到route 前面
    m939594960
        6
    m939594960  
    OP
       May 25, 2015
    @yangmls 懂了 厉害
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3206 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 03:15 · PVG 11:15 · LAX 20:15 · JFK 23:15
    ♥ Do have faith in what you're doing.