gteixeira/router

经典 CoffeeCode Router 的分支

v1.0.0 2024-06-18 07:02 UTC

This package is auto-updated.

Last update: 2024-09-18 07:36:08 UTC


README

Source Code PHP from Packagist

通过 Composer 可用

composer require gteixeira/router

注释

添加了对 PHP-DI 的支持,但 Router 的用法没有变化(所有配置和使用方式仍然按照文档进行,只需要在路由文件和控制器文件中做出更改,以便使用 PHP-DI 解决构造函数的依赖性)。

改进展望:将 feat 的实现逻辑抽象为接口,等待一个方法(例如 get($id),其中 $id 代表带有命名空间类名,例如 CoffeeCode\Router\Router)返回对象实例 $id(类似于 PHP-DI 的方式),允许用户选择遵循接口约定的其他依赖注入容器实现。

更多详情请查看原始文档!!

文档

之前

路由

<?php

use CoffeeCode\Router\Router;

$router = new Router("https://www.youdomain.com");

/**
 * routes
 * The controller must be in the namespace Test\Controller
 */
$router->namespace("Test")->group("name");

$router->get("/", "Name:home", "name.home");
$router->get("/hello", "Name:hello", "name.hello");
$router->get("/redirect", "Name:redirect", "name.redirect");

/**
 * This method executes the routes
 */
$router->dispatch();

/*
 * Redirect all errors
 */
if ($router->error()) {
    $router->redirect("name.hello");
}

命名控制器

<?php

class Name
{
    public function __construct($router)
    {
        $this->router = $router;
    }

    public function home(): void
    {
        echo "<h1>Home</h1>";
        echo "<p>", $this->router->route("name.home"), "</p>";
        echo "<p>", $this->router->route("name.hello"), "</p>";
        echo "<p>", $this->router->route("name.redirect"), "</p>";
    }

    public function redirect(): void
    {
        $this->router->redirect("name.hello");
    }
}

之后

路由

<?php

use DI\ContainerBuilder;
use DI\Container;
use CoffeeCode\Router\Router;

$builder = new ContainerBuilder();
$builder->addDefinitions([
  Router::class => function (Container $container) {
          return new Router(projectUrl: "https://www.youdomain.com", container: $container);
      }
]);

$container = $builder->build();

$router = $container->get(Router::class);

/**
 * routes
 * The controller must be in the namespace Test\Controller
 */
$router->namespace("Test")->group("name");

$router->get("/", "Name:home", "name.home");
$router->get("/hello", "Name:hello", "name.hello");
$router->get("/redirect", "Name:redirect", "name.redirect");

/**
 * This method executes the routes
 */
$router->dispatch();

/*
 * Redirect all errors
 */
if ($router->error()) {
    $router->redirect("name.hello");
}

命名控制器

<?php

use CoffeeCode\Router\Router;

class Name
{
    public function __construct(
        protected Router $router
    ) { }

    public function home(): void
    {
        echo "<h1>Home</h1>";
        echo "<p>", $this->router->route("name.home"), "</p>";
        echo "<p>", $this->router->route("name.hello"), "</p>";
        echo "<p>", $this->router->route("name.redirect"), "</p>";
    }

    public function redirect(): void
    {
        $this->router->redirect("name.hello");
    }
}

致谢

许可协议

MIT 许可证(MIT)。有关更多信息,请参阅许可文件