从uri获取参数

时间:2013-05-15 13:08:42

标签: php url methods controller mapping

我设置了一个简单的路由器类,它提取以下

  1. 控制器
  2. 动作
  3. 参数
  4. 类路由器{

    private $uri;
    private $controller;
    private $method;
    private $params;
    
    public function __construct($uri) {
        $this->uri = $uri;
        $this->method = 'index';
        $this->params = array();
    }
    
    public function map() {
        $uri = explode('/', $this->uri);
        if (empty($uri[0])) {
            $c = new Config('app');
            $this->controller = $c->default_controller;
        } else {
            if (!empty($uri[1]))
                $this->method = $uri[1];
            // how about the parameters??
        }
    }
    

    }

    那个简单的$router->map()可以从这个uri http://domain.com/users/edit/2

    给我正确的控制器,动作和单个参数

    这很好,但如果我需要在url中存储更多参数,如下所示: http://domain.com/controller/action/param/param2/param3

    如果我不知道将传递多少参数,如何将它们推送到$parms

1 个答案:

答案 0 :(得分:2)

您知道数组的前两个值是控制器操作,之后的所有内容都是 param

因此,您可以使用array_shift($uri)获取前2个,剩余的$uri将成为您的参数。

public function map() {
    $uri = explode('/', $this->uri);

    // shift element off beginning of array.

    $controller = array_shift($uri);
    $action = array_shift($uri);

    // your $uri variable will not only contain the params.

    if (empty($uri[0])) {
        $c = new Config('app');
        $this->controller = $c->default_controller;
    } else {
        if (!empty($uri[1]))
            $this->method = $uri[1];
        // how about the parameters??
    }
}