Symfony组件 - 路由

时间:2017-01-25 23:43:35

标签: php routing url-routing symfony

问题:

说真的,我用得好吗?它有效,但我不确定使用Symfony组件的正确方法。有人像我一样使用这些组件吗?

  1. 我不确定dispatch()
  2. 中的异常处理
  3. 我不确定在下面的代码中使用$ _SERVER [' REQUEST_URI'] ...
  4. 我的 composer.json

    {
        "require": {
            "symfony/routing": "^3.2"
        }
    }
    

    我的 index.php

    <?php
    
    include './vendor/autoload.php';
    
    use Symfony\Component\Routing\Exception\MethodNotAllowedException;
    use Symfony\Component\Routing\Exception\ResourceNotFoundException;
    use Symfony\Component\Routing\Matcher\UrlMatcher;
    use Symfony\Component\Routing\RequestContext;
    use Symfony\Component\Routing\Route;
    use Symfony\Component\Routing\RouteCollection;
    
    use Symfony\Component\HttpFoundation\Request;
    
    class Christopher {
        public $context;
        public $routes;
    
        public function __construct() {
            $context = new RequestContext();
            $this->context = $context->fromRequest(Request::createFromGlobals());
            $this->routes = new RouteCollection();
        }
    
        public function route($methods, $path, $controller) {
            $this->routes->add($path, new Route(
                $path,
                [
                    '_controller' => $controller
                ],
                [
                    'id' => '[0-9]'
                ],
                [],
                '',
                [],
                $methods
            ));
        }
    
        public function dispatch() {
            $matcher = new UrlMatcher($this->routes, $this->context);
    
            try {
                $matcher = $matcher->match($_SERVER['REQUEST_URI']);
    
                call_user_func_array($matcher['_controller'], array_slice($matcher, 1, -1));
            } catch (MethodNotAllowedException $e) {
                echo 'Route method is not allowed.';
            } catch (ResourceNotFoundException $e) {
                echo 'Route does not exist.';
            }
        }
    }
    
    $christopher = new Christopher();
    
    $christopher->route('GET', '/posters', function () {
        echo '<a href="/posters/1">1. Poster</a>';
    });
    
    $christopher->route('GET', '/posters/{id}', function ($id) {
        echo 'ID - ' . $id;
    });
    
    $christopher->dispatch();
    

0 个答案:

没有答案