wilsonneto-dev/express-router

PHP 最简单的路由器

1.0.1 2022-09-18 20:30 UTC

This package is auto-updated.

Last update: 2024-09-25 20:35:30 UTC


README

🎈 以最简单、最容易、最极简的方式 😃 在纯 PHP 应用中创建路由

在项目中安装它

composer require wilsonneto-dev/express-router

在项目中使用它

require_once __DIR__ . "/vendor/autoload.php";

$router = new ExpressRouter\Router();

// ... register your routes...

$router->route(isset($_GET["path"]) ? $_GET["path"] : "");

创建路由的简单示例

require_once __DIR__ . "/vendor/autoload.php";

$router = new ExpressRouter\Router();

$router->get("/", function ($req, $res) {
    return $res->response(array("ok" => true, "tip" => "Use /articles"));
});

$router->get("/articles", function ($req, $res) {
    return $res->response(array("example" => "list of articles"));
});

$router->get("/articles/:id", function ($req, $res) {
    return $res->response(array("example" => "details of the article with id " . $req->parameters["id"]));
});

$router->get("/articles/:id/comments", function ($req, $res) {
    return $res->response(array("example" => "list of comments of the article with id " . $req->parameters["id"]));
});

$router->post("/articles", function ($req, $res) {
    return $res->response(array("example" => "create a new article"));
});

$router->put("/articles/:id", function ($req, $res) {
    return $res->response(array("example" => "update the article with id " . $req->parameters["id"]));
});

$router->route(isset($_GET["path"]) ? $_GET["path"] : "");

您需要启用重写模块并有一个如下的 .htaccess 文件

<Files app.ini> 
    Order Allow,Deny
    Deny from all
</Files>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?path=$1 [NC,L,QSA]

示例项目

https://github.com/wilsonneto-dev/express-router-example

包网站

https://wilsonneto-dev.github.io/express-router/

Packagist

https://packagist.org.cn/packages/wilsonneto-dev/express-router

请求和响应对象

您的路由回调将接收两个对象,包含所有请求信息的请求;以及负责准备响应的响应对象。

class Request {
    // the route parameters
    public ?Array $parameters;

    // query parameters 
    public ?Array $query = null;

    // body payload
    public $body = null;

    // the request route
    public string $route = "";

    // the request method
    public string $method = "";
}
class Response {
    // use this method to control the response status code, default 200. 
    public function status(int $new_status_code);

    // use this method to return the response
    public function response(Array $response);
}

是的,就这么简单!
生活有时可以很简单 ✨