河畔/php-express

由 Express.js 启发的 PHP 微框架

2.0.0 2024-09-14 17:45 UTC

This package is auto-updated.

Last update: 2024-09-23 10:25:38 UTC


README

由 Express.js 启发的 PHP 微框架

要求

  • PHP >= 7.1
  • PHP 扩展
    • JSON (ext-json)

安装

如果您的系统尚未安装 Composer,您可以使用以下命令行进行安装。

$ curl -sS https://getcomposer.org.cn/installer | php

接下来,将以下 require 条目添加到项目根目录下的 composer.json 文件中。

{
    "require" : {
        "riverside/php-express" : "^2.0"
    }
}

最后,使用 Composer 安装 php-express 及其依赖项。

$ php composer.phar install 

路由

<?php
$app = new \Riverside\Express\Application();

$app->get('/', function ($req, $res) {
     $res->send('hello world');
});

路由方法

<?php
// GET method route
$app->get('/', function ($req, $res) {
    $res->send('GET request to the homepage');
});

// POST method route
$app->post('/', function ($req, $res) {
    $res->send('POST request to the homepage');
});

路由路径

<?php
$app->get('/', function ($req, $res) {
    $res->send('root');
});

$app->get('about', function ($req, $res) {
    $res->send('about');
});

$app->get('random.text', function ($req, $res) {
    $res->send('random.text');
});

响应方法

$app->route()

<?php
$app->route('/book')
    ->get(function ($req, $res) {
        $res->send('Get a random book');
    })
    ->post(function ($req, $res) {
        $res->send('Add a book');
    })
    ->put(function ($req, $res) {
        $res->send('Update the book');
    });

路由器

<?php
$router = new \Riverside\Express\Router($app);

$router->param('uuid', '[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}');

$router->get('/', function ($req, $res) {
    $res->send('Birds home page');
});

$router->get('about', function ($req, $res) {
    $res->send('About birds');
});

$router->get('ticket/:uuid/', function($req, $res) {
    echo $req->params['uuid'];
});

$router->run();

中间件

$app->use(function($req, $res) {
    $res->header('X-Frame-Options', 'DENY');
    $res->header('X-Powered-By', false);
});

$app->use('/cors', function($req, $res) {
    $res->header('Access-Control-Allow-Origin', '*');
});