如何在PHP中创建路由器?

Hyp*_*ami 5 php url-rewriting url-routing

我正在为我的一个项目开发一个路由器,我需要做以下事情:

例如,假设我们有这个设置路由数组:

$routes = [
    'blog/posts' => 'Path/To/Module/Blog@posts',
    'blog/view/{params} => 'Path/To/Module/Blog@view',
    'api/blog/create/{params}' => 'Path/To/Module/API/Blog@create'
];
Run Code Online (Sandbox Code Playgroud)

然后,如果我们通过这个URL:http://localhost/blog/posts它将调度blog/posts路线 - 这没关系.

现在,当涉及到需要参数的路由时,我所需要的只是一种实现传递参数的能力的方法(即http://localhost/blog/posts/param1/param2/param3能够预先api创建http://localhost/api/blog/create/到目标API调用,但我很难过.

先感谢您.

Pro*_*ock 6

这是基本的东西,当前路由可以有一个模式,如果应用程序路径以该模式开始,那么它就是匹配.路径的其余部分变成了参数.

<?php
class Route
{
    public $name;
    public $pattern;
    public $class;
    public $method;
    public $params;
}

class Router
{
    public $routes;

    public function __construct(array $routes)
    {
        $this->routes = $routes;
    }

    public function resolve($app_path)
    {
        $matched = false;
        foreach($this->routes as $route) {
            if(strpos($app_path, $route->pattern) === 0) {
                $matched = true;
                break;
            }
        }

        if(! $matched) throw new Exception('Could not match route.');

        $param_str = str_replace($route->pattern, '', $app_path);
        $params = explode('/', trim($param_str, '/'));
        $params = array_filter($params);

        $match = clone($route);
        $match->params = $params;

        return $match;
    }
}

class Controller
{
    public function action()
    {
        var_dump(func_get_args());
    }
}

$route = new Route;
$route->name    = 'blog-posts';
$route->pattern = '/blog/posts/';
$route->class   = 'Controller';
$route->method  = 'action';

$router = new Router(array($route));
$match  = $router->resolve('/blog/posts/foo/bar');

// Dispatch
if($match) {
    call_user_func_array(array(new $match->class, $match->method), $match->params);
}
Run Code Online (Sandbox Code Playgroud)

输出:

array (size=2)
  0 => string 'foo' (length=3)
  1 => string 'bar' (length=3)
Run Code Online (Sandbox Code Playgroud)