joségarcia/router

简单的PHP路由器,模仿Express路由器的行为

2.1.2 2024-09-28 17:50 UTC

This package is auto-updated.

Last update: 2024-09-28 17:51:54 UTC


README

一个简单的PHP路由器,受Express和Laravel启发。

描述

这是一个简单的PHP路由器,受Express和Laravel启发。它允许您定义路由及其处理器,然后运行路由器来匹配当前请求并执行相应的处理器。

安装

composer require josegarcia/router

用法

<?php

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

use Garcia\Router;

// Example of a simple route
Router::addRoute('GET', '/health', fn () => 'Hello, world!');

// Example of a route with a parameter
Router::addRoute('GET', '/health/:id', fn ($params) => "User ID: {$params['id']}");

// Example of a route that returns a JSON response
Router::get( '/api/health/:id', fn ($params) => ['id' => $params['id'], 'name' => 'John Doe', 'email' => 'john@example.com']);

// Example of rendering a view
Router::get('/view', fn () => [
    // we need to pass the view name and the data to be rendered as a template
    'view' => 'template',
    // we can also pass the path to the views directory
    'path' => 'views',
    // we can also pass the data to be rendered
    'data' => [
        'name' => 'John Doe'
    ]
]);

Router::post('/health', fn ($params) => "Hello, {$params['name']} {$params['last']}!");

// Example of rendering
Router::get('/redirect', fn () => redirect('http://www.example.com'));

Router::run();

API

该路由器有以下方法:get、post、put、patch、delete、options、head、any、addRoute、run、redirect、view、json和render。

get、post、put、patch、delete、options、head、any

这些方法用于定义路由。它们接受两个参数:路由和处理程序。路由可以包含参数,参数由冒号后跟参数名称定义。处理程序可以是函数或字符串。如果它是字符串,则假定它是要调用的函数的名称。

addRoute

此方法用于定义路由。它接受三个参数:方法、路由和处理程序。路由可以包含参数,参数由冒号后跟参数名称定义。处理程序可以是函数或字符串。如果它是字符串,则假定它是要调用的函数的名称。

run

此方法用于运行路由器。它不接受任何参数。

redirect

此方法用于重定向到另一个URL。它接受一个参数:要重定向到的URL。

view

此方法用于渲染视图。它接受一个参数:要渲染的视图的名称。

json

此方法用于返回JSON响应。它接受一个参数:作为JSON返回的数据。

render

此方法用于渲染视图。它接受一个参数:要渲染的视图的名称。

示例

您可以在示例目录中找到更多示例。

测试

您可以使用以下命令运行测试

composer test

贡献

欢迎拉取请求。对于重大更改,请首先打开一个问题以讨论您想要更改的内容。

许可

MIT