richardandrade/php_router

该包的最新版本(dev-main)没有可用的许可信息。

一个简单的应用路由管理器

dev-main 2023-06-30 20:19 UTC

This package is auto-updated.

Last update: 2024-09-30 01:41:21 UTC


README

一个简单的php路由库,用于管理您的APIs/Apps路由。

此库仅适用于学习目的或小型项目。


如何安装它

composer require richardandrade/php_router

如何使用它


1. 在您的入口控制器中,您需要用源(或应用)命名空间作为参数实例化路由类

use RichardAndrade\PhpRouter;

$router = new Router('app\example\\');

2. 初始化类后,您需要定义应用程序的路由,我建议创建一个名为 'routes.php' 的新文件,然后在入口控制器中包含它

include_once('routes.php');
//in 'routes.php' file

$router->setRoute([
      'path' => '/home', //Route path
      'methods' => ['GET'], //Here you'll need to define the allowed HTTP Methods as an array (e.g ['GET','POST','PUT'])
      'controller' => 'MyController' //The name of the controller responsible for this route
]);

3. 最后,在定义路由并将文件包含在入口控制器中后,调用以下方法来启动路由器

$router->run();

最终结果(索引文件)应该类似于

use RichardAndrade\PhpRouter;

$router = new Router('app\example\\');

include_once('routes.php');

$router->run();

定义动态路由


使用此库,您还可以定义动态路由。此类路由将使您的应用程序接收请求URI中定义的任何参数。

//routes such as 'myapp.com/article/1', where '1' could be the article ID, can be configured as shown bellow

$router->setRoute([
      'path' => '/article/{id}', //in this case I used 'id', this will be the key name for the 'params' associative array
      'methods' => ['GET'],
      'controller' => 'ArticlesController'
]);

//after that, your controller will be able to receive the defined params

class ArticlesController {
  public funtion __construct(array $params)
  {
  }
}

//the 'params' variable will provide, in this example, ['id' => '1']



额外:设置头部信息


此库还提供了一种简单的方法来在控制器中定义响应头。

use RichardAndrade\PhpRouter;

class ArticlesController {
    public function example()
    {
        Router::setHeaders([
              'Content-type' => 'application/xml',
              'Access-Control-Allow-Origin' => 'https://myapp.com'
        ]);
    }
}