delight-im/router

PHP 的路由器。简单、轻量级、方便。

v3.1.1 2019-06-14 12:33 UTC

This package is auto-updated.

Last update: 2024-08-24 07:13:55 UTC


README

PHP 的路由器。简单、轻量级、方便。

要求

  • PHP 5.6.0+

安装

  1. 通过 Composer 包含库 [?]

    $ composer require delight-im/router
    
  2. 包含 Composer 自动加载器

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

用法

  1. 在您的 Web 服务器上启用 URL 重写

    • Apache(在 .htaccesshttpd.conf 中)

      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteRule . index.php [L]
      
    • Nginx(在 nginx.conf 中)

      try_files $uri /index.php;
      
  2. 创建一个新的 Router 实例

    • 用于网站根目录

      $router = new \Delight\Router\Router();
    • 用于任何子目录

      $router = new \Delight\Router\Router('/my/base/path');
  3. 添加一些路由并将其映射到匿名函数或闭包

    • 静态路由

      $router->get('/', function () {
          // do something
      });
    • 动态路由(带有参数)

      $router->get('/users/:id/photo', function ($id) {
          // get the photo for user `$id`
      });

      在 URL 中匹配的参数值可以作为回调中的参数捕获。

    • 支持多种请求方法的路由

      $router->any([ 'POST', 'PUT' ], '/users/:id/address', function ($id) {
          // update the address for user `$id`
      });
  4. 将路由映射到控制器方法,以实现更复杂的回调

    // use static methods
    $router->get('/photos/:id/convert/:mode', [ 'PhotoController', 'myStaticMethod' ]);
    
    // or
    
    // instance methods
    $router->get('/photos/:id/convert/:mode', [ $myPhotoController, 'myInstanceMethod' ]);
  5. 注入参数以访问更多值和对象(添加到路由中匹配的参数之前)

    class MyController {
    
        public static function someStaticMethod($database, $uuid) {
            // do something
        }
    
    }

    $database = new MyDatabase();
    
    // ...
    
    $router->delete('/messages/:uuid', [ 'MyController', 'someStaticMethod' ], [ $database ]);

贡献

欢迎所有贡献!如果您想做出贡献,请首先创建一个问题,以便您的功能、问题或疑问可以得到讨论。

许可

本项目根据 MIT 许可证 的条款许可。