hxgf/xprss

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

0.0.4 2022-04-24 23:20 UTC

This package is auto-updated.

Last update: 2024-09-22 22:42:51 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