快速、无偏见的、极简主义PHP Web框架

0.0.4 2022-04-24 23:20 UTC

This package is auto-updated.

Last update: 2024-09-22 22:40:41 UTC


README

这几乎是 express-php 的直接克隆,它试图克隆 NodeJS ExpressJS 框架 的编码风格。它没有事件循环,只是模仿了ExpressJS提供的方法和助手名称。

安装

要求:PHP >= 7.0 和 Apache。

composer require jyoungblood/xprss:0.0.4@dev

然后,将 .htaccess 复制到您站点的根目录

cp vendor/jyoungblood/xprss/.htaccess ./.htaccess

(如果您不想复制,可以在新的 .htaccess 文件中放入以下内容)

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

(您也可以为 nginx 执行此操作)

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /index.php?route=$1 break;
  }
}

使用/示例示例初始化

这里有一个如何初始化的快速示例。如果您对更多样板代码感兴趣,请查看 [文档] 以获取更多选项,同时 [app中的index.php文件] 也包含一个完整示例,以及 [create-xprss-app] 作为一个合理的样板代码启动套件。

<?php
include __DIR__.'/vendor/autoload.php';

use XPRSS\Application;
use XPRSS\Router;

$app = new Application();
$router = new Router();

$router->get('/', function($req, $res) {
	$res->send('<h1>Hello Cleveland!</h1>');
});

$app->listen($router);
?>

路由

使用 Router 实例处理路由,例如

$router = new Router();
$router->get('/', function($req, $res) {
    // This will be called when someone goes to the main page using GET method.
});

您也可以使用 post() 而不是 get() 来处理 POST 请求。对于 put() 和 delete() 也是如此。

具有动态参数的路由

您可以使用参数来路由动态URL,例如

$router = new Router();
$router->get('/:something/:else', function($req, $res) {
    /**
     * Now let's imagine someone enters to URL: /hello/bye, then:
     *
     * $req->params->something will contain 'hello'
     * $req->params->else will contain 'bye'
     */
});

响应

如果您正在开发API,例如,您可以通过简单地这样做来发送JSON

$router->post('/', function($req, $res) {
	$res->json(array(
		'error'		=> false,
		'message'	=> 'Hello'
	));
});

您还可以使用以下方式发送自定义 HTTP 响应代码

$router->post('/', function($req, $res) {
	$res->status(201)->json({
		'error'		=> false,
		'message'	=> 'Created!'
	});
});

提示:在该存储库中的 index.php 文件中还有一些其他示例。

静态文件

如果您希望提供静态文件(如图像、仅HTML),可以使用

// If you visit /static/image.png, this will return the file views/public/image.png
$router->use('/static', $app->static('views/public'));

模板引擎

您需要自己处理模板...在某个时候,我们将有一个指南,说明如何支持各种模板引擎(jade/pug、handlebars、twig等)

我们希望尽可能简单

// Configure the engine to Pug
$app->set('view engine','pug');

// Jade was renamed to Pug, but we recognize it ;)
$app->set('view engine','jade');

// Or Mustache
$app->set('view engine','mustache');

// Set the path to the template files
$app->set('views','./views/pug');

// Now you can do something like this
$router->get('/', function($req, $res) {
	$res->render('index.jade');
});

// Or this
$router->get('/users/:username', function($req, $res) {
	$res->render('index.jade', array(
		'name'	=> $req->params->username
	));

	// Now in jade, you can use #{name} to get that variable!
});

请求信息

  • 请求体:$res->body
  • 查询字符串:$req->query
  • cookie:$req->cookies
  • 所有请求头:$req->headers