0

I setup a simple router class that extracts the following

  1. Controller
  2. Action
  3. Parameters

class Router {

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??
    }
}

}

That simple $router->map() can give me the right controller, action and a single parameter from this uri http://domain.com/users/edit/2

That is quite okay, but what if I needed to store more parameters in the url like this : http://domain.com/controller/action/param/param2/param3

How do I push them to $parms if I don't know how many parameters will be passed.

4

1 回答 1

2

您知道数组的第一个两个值是控制器动作,之后的所有内容都将是一个参数

所以你可以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??
    }
}
于 2013-05-15T13:12:45.087 回答