starbug/routing

为 Starbug PHP 框架设计的路由器。

v0.9.2 2024-07-11 19:25 UTC

This package is auto-updated.

Last update: 2024-09-11 19:54:19 UTC


README

Starbug PHP 框架的路由库。

设置

首先实现 RouteProviderInterface 来定义路由。

namespace MyApp;

use Starbug\Routing\RouteProviderInterface;
use Starbug\Routing\Controller;
use Starbug\Routing\Controller\ViewController;

class RouteProvider implements RouteProviderInterface {
  /**
   * @param Route $routes This is the root path "/"
   */
  public function configure(Route $routes) {
    // Configure the root path
    $routes->setController(ViewController::class);
    $routes->setOption("view", "home.html");

    // This Route is added from the root so the full path is "/" + "home" = "/home"
    $home = $routes->addRoute("home", ViewController::class, [
      "view" => "home.html"
    ]);
    $routes->addRoute("missing", [Controller::class, "missing"]);
    $routes->addRoute("forbidden", [Controller::class, "forbidden"]);

    // Adding from the above "/home" Route, the full path will  be "/home/test"
    $home->addRoute("/test", ViewController::class, [
      "view" => "test.html"
    ]);
  }
}

然后创建一个包含一个或多个提供程序实例的路由配置。

namespace MyApp;

use Starbug\Routing\Configuration;

$config = new Configuration();
$provider = new RouteProvider();

$config->addProvider($provider);

接下来使用配置对象来创建一个 RouteStorageInterface 实现。我们将使用包含的 FastRouteStorage。

namespace MyApp;

use Starbug\Routing\FastRouteStorage;

$dispatcher = FastRouteStorage::createDispatcher($config);
$storage = new FastRouteStorage($dispatcher, $access);

现在我们可以实例化一个 Router。

namespace MyApp;

use Starbug\Routing\Router;

// Must be instance of Invoker\InvokerInterface
$invoker;

$router = new Router($invoker);
$router->addStorage($storage);

用法

您可以直接使用路由器或使用提供的 PSR-15 中间件(RoutingMiddleware 和 ControllerMiddleware)。

// Pass in a PSR-7 ServerRequestInterface instance and get back the route.
$route = $this->router->route($request);