nickstuer/easy-router

一个简单易用的PHP路由器。

v0.0.1 2015-12-09 02:38 UTC

This package is not auto-updated.

Last update: 2024-09-11 23:59:56 UTC


README

简介

该项目目前没有维护!

这是一个主要用于学习目的的基本PHP路由器。当你不希望应用的路由功能与整个应用紧密耦合时,它工作得很好。

支持PHP 7+。

如果你有任何建议或错误修复,请随意修改。

示例用法

使用addRoute()指定当匹配到路由时调用的控制器和控制器方法。

要匹配通配符,请在路由路径中使用以下短语

  • (任何) - 匹配任意组合的大小写字母和数字。
  • (整数) - 仅匹配整数。
  • (abc) - 匹配任意组合的大小写字母。

Easy Router的典型使用

include (__DIR__ . '/vendor/autoload.php');

use \NickStuer\EasyRouter\Route as Route;

$routeManager = new \NickStuer\EasyRouter\RouteManager();
$dispatcher = new \NickStuer\EasyRouter\Dispatcher($routeManager);

$routeManager->addRoute(new Route('get', '/', 'ControllerToCall@methodToCall'));
$routeManager->addRoute(new Route('get', '/about', 'PagesController@showAbout'));
$routeManager->addRoute(new Route('get', '/contact', 'PagesController@showContact'));
$routeManager->addRoute(new Route('get', '/profile/(abc)', 'ProfileController@showProfile'));

try {
    $dispatcher->dispatch();
} catch (\NickStuer\EasyRouter\Exceptions\RouteNotFoundException $e) {
    echo "Route Not Found - 404";
    exit;
} catch (\NickStuer\EasyRouter\Exceptions\MethodNotAllowedException $e) {
    echo "Method Not Allowed - 405";
    exit;
}

$routeInfo = $dispatcher->getMatchedRoute();

/**
 * It's recommended that you use a DI container to create the controller class to
 * automatically insert the required dependencies.
 */
$controller = new $routeInfo['controller'];
$method = $routeInfo['method'];
$controller->$method($routeInfo['variables']);

许可证

Easy Router遵循MIT许可证