PHP 路由包

1.1.3 2024-08-06 17:18 UTC

This package is auto-updated.

Last update: 2024-09-06 17:33:43 UTC


README

PHP 路由包

基本概念

路由包是一个实用程序,一旦所有 HTTP 请求都重定向到一个入口点,就可以使用一个 --易于理解且友好 -- 的接口配置和组织这些请求。

例如,给定以下 .htaccess 文件

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

其中所有请求(除了导入图像、CSS 或 JS 脚本的请求)都被重定向到位于项目根目录的 index.php 文件,所有请求都集中在入口点,这样你就可以使用 Router 来简化你的生活。

用法

在应用的入口点

require __DIR__ . '/vendor/autoload.php';

// instantiate the container
$container = new MDP\Container\Container();

// bind whatever you need
$container->set(
    MyAbstract::class, 
    MyConcrete::class
);

// create the Router instance passing the controllers and the container
$router = Router::create([ControllerClasses::class], $container);

// direct the request to the rigth place
$router->direct();

在控制器中

<?php

namespace MDP\Test\Router;

use MDP\Test\Router\MockedService\MockedServiceApi;
use MDP\Router\Attributes\Get;

readonly class ControllerClass
{
    public function __construct(private MyAbstract $service)
    {
        //
    }

    // We decorate methods with Verb Attributes
    #[Get("/")]
    public function mockMethod(): bool
    {
        return true;
    }
}