mmcp/flight

Flight 是一个快速、简单、可扩展的 PHP 框架。Flight 允许您快速轻松地构建 RESTful 网络应用程序。此软件包已符合 PSR-0 规范,并且对 composer 友好,同时对 mmcp 项目所需的某些小改动进行了处理。

1.2.0 2013-11-09 07:20 UTC

This package is not auto-updated.

Last update: 2024-09-24 02:09:06 UTC


README

Flight 是一个快速、简单、可扩展的 PHP 框架。Flight 允许您快速轻松地构建 RESTful 网络应用程序。

require 'flight/Flight.php';

Flight::route('/', function(){
    echo 'hello world!';
});

Flight::start();

了解更多

需求

Flight 需要 PHP 5.3 或更高版本。

许可

Flight 在 MIT 许可下发布。

安装

1. 下载 并将 Flight 框架文件解压缩到您的网页目录。

2. 配置您的网络服务器。

对于 Apache,使用以下内容编辑您的 .htaccess 文件

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

对于 Nginx,在服务器声明中添加以下内容

server {
    location / {
        try_files $uri $uri/ /index.php;
    }
}

3. 创建您的 index.php 文件。

首先包含框架。

require 'flight/Flight.php';

然后定义一个路由并分配一个函数来处理请求。

Flight::route('/', function(){
    echo 'hello world!';
});

最后,启动框架。

Flight::start();

路由

Flight 中的路由是通过匹配 URL 模式与回调函数来完成的。

Flight::route('/', function(){
    echo 'hello world!';
});

回调可以是任何可调用的对象。因此,您可以使用常规函数

function hello(){
    echo 'hello world!';
}

Flight::route('/', 'hello');

或者类方法

class Greeting {
    public static function hello() {
        echo 'hello world!';
    }
}

Flight::route('/', array('Greeting','hello'));

路由是按照定义的顺序匹配的。首先匹配到请求的路由将被调用。

方法路由

默认情况下,路由模式与所有请求方法匹配。您可以通过在 URL 前放置一个标识符来响应特定方法。

Flight::route('GET /', function(){
    echo 'I received a GET request.';
});

Flight::route('POST /', function(){
    echo 'I received a POST request.';
});

您还可以使用 | 分隔符将多个方法映射到单个回调

Flight::route('GET|POST /', function(){
    echo 'I received either a GET or a POST request.';
});

正则表达式

您可以在路由中使用正则表达式

Flight::route('/user/[0-9]+', function(){
    // This will match /user/1234
});

命名参数

您可以在路由中指定命名参数,这些参数将被传递到回调函数。

Flight::route('/@name/@id', function($name, $id){
    echo "hello, $name ($id)!";
});

您还可以使用 : 分隔符在命名参数中包含正则表达式

Flight::route('/@name/@id:[0-9]{3}', function($name, $id){
    // This will match /bob/123
    // But will not match /bob/12345
});

可选参数

您可以通过将段包裹在括号中来指定用于匹配的可选命名参数。

Flight::route('/blog(/@year(/@month(/@day)))', function($year, $month, $day){
    // This will match the following URLS:
    // /blog/2012/12/10
    // /blog/2012/12
    // /blog/2012
    // /blog
});

未匹配的任何可选参数将以 NULL 的形式传递。

通配符

匹配仅在单个 URL 段上执行。如果您想匹配多个段,可以使用 * 通配符。

Flight::route('/blog/*', function(){
    // This will match /blog/2000/02/01
});

要将所有请求路由到单个回调,您可以这样做

Flight::route('*', function(){
    // Do something
});

传递

您可以通过从回调函数中返回 true 将执行传递到下一个匹配的路由。

Flight::route('/user/@name', function($name){
    // Check some condition
    if ($name != "Bob") {
        // Continue to next route
        return true;
    }
});

Flight::route('/user/*', function(){
    // This will get called
});

扩展

Flight 被设计成可扩展的框架。该框架包含一组默认方法和组件,但它允许您映射自己的方法、注册自己的类,甚至覆盖现有的类和方法。

映射方法

要映射您自己的自定义方法,您使用 map 函数

// Map your method
Flight::map('hello', function($name){
    echo "hello $name!";
});

// Call your custom method
Flight::hello('Bob');

注册类

要注册您自己的类,您使用 register 函数

// Register your class
Flight::register('user', 'User');

// Get an instance of your class
$user = Flight::user();

register 方法还允许您将参数传递到类构造函数。因此,当您加载自定义类时,它将预先初始化。您可以通过传递额外的数组来定义构造函数参数。以下是一个加载数据库连接的示例

// Register class with constructor parameters
Flight::register('db', 'Database', array('localhost','mydb','user','pass'));

// Get an instance of your class
// This will create an object with the defined parameters
//
//     new Database('localhost', 'mydb', 'user', 'pass');
//
$db = Flight::db();

如果你传入额外的回调参数,它将在类构造后立即执行。这允许你为新的对象执行任何设置程序。回调函数接受一个参数,即新对象的实例。

// The callback will be passed the object that was constructed
Flight::register('db', 'Database', array('localhost', 'mydb', 'user', 'pass'), function($db){
    $db->connect();
});

默认情况下,每次你加载类时,你都会得到一个共享实例。要获取类的新的实例,只需将 false 作为参数传入。

// Shared instance of Database class
$shared = Flight::db();

// New instance of Database class
$new = Flight::db(false);

请注意,映射方法比注册类有优先级。如果你使用相同的名称声明两者,只有映射方法将被调用。

覆盖

Flight 允许你覆盖其默认功能以满足你的需求,而无需修改任何代码。

例如,当 Flight 无法将 URL 与路由匹配时,它会调用 notFound 方法,发送通用的 HTTP 404 响应。你可以通过使用 map 方法来覆盖此行为。

Flight::map('notFound', function(){
    // Display custom 404 page
    include 'errors/404.html';
});

Flight 还允许你替换框架的核心组件。例如,你可以用你自己的自定义类替换默认的 Router 类。

// Register your custom class
Flight::register('router', 'MyRouter');

// When Flight loads the Router instance, it will load your class
$myrouter = Flight::router();

但是,框架方法如 mapregister 不能被覆盖。如果你尝试这样做,将会得到一个错误。

过滤

Flight 允许你在方法被调用前后对其进行过滤。没有预定义的钩子需要记忆。你可以过滤任何默认框架方法以及任何你映射的自定义方法。

一个过滤器函数看起来像这样

function(&$params, &$output) {
    // Filter code
}

使用传入的变量,你可以操作输入参数和/或输出。

要在方法之前运行一个过滤器,你可以这样做

Flight::before('start', function(&$params, &$output){
    // Do something
});

要在方法之后运行一个过滤器,你可以这样做

Flight::after('start', function(&$params, &$output){
    // Do something
});

你可以向任何方法添加任意多的过滤器。它们将按声明的顺序调用。

以下是一个过滤过程的示例

// Map a custom method
Flight::map('hello', function($name){
    return "Hello, $name!";
});

// Add a before filter
Flight::before('hello', function(&$params, &$output){
    // Manipulate the parameter
    $params[0] = 'Fred';
});

// Add an after filter
Flight::after('hello', function(&$params, &$output){
    // Manipulate the output
    $output .= " Have a nice day!";
});

// Invoke the custom method
echo Flight::hello('Bob');

这应该会显示

Hello Fred! Have a nice day!

如果你定义了多个过滤器,你可以通过在任何过滤器函数中返回 false 来中断链。

Flight::before('start', function(&$params, &$output){
    echo 'one';
});

Flight::before('start', function(&$params, &$output){
    echo 'two';

    // This will end the chain
    return false;
});

// This will not get called
Flight::before('start', function(&$params, &$output){
    echo 'three';
});

注意,核心方法如 mapregister 不能被过滤,因为它们是直接调用的,而不是动态调用的。

变量

Flight 允许你保存变量,以便在应用程序的任何地方使用。

// Save your variable
Flight::set('id', 123);

// Elsewhere in your application
$id = Flight::get('id');

要检查变量是否已设置,你可以这样做

if (Flight::has('id')) {
     // Do something
}

你可以通过这样做来清除变量

// Clears the id variable
Flight::clear('id');

// Clears all variables
Flight::clear();

Flight 还使用变量进行配置。

Flight::set('flight.log_errors', true);

视图

Flight 默认提供了一些基本的模板功能。要显示视图模板,请使用模板文件名调用 render 方法,并可选地传入模板数据。

Flight::render('hello.php', array('name' => 'Bob'));

你传入的模板数据会自动注入到模板中,可以像局部变量一样引用。模板文件只是 PHP 文件。如果 hello.php 模板文件的 内容是

Hello, '<?php echo $name; ?>'!

输出将是

Hello, Bob!

你也可以通过使用设置方法手动设置视图变量

Flight::view()->set('name', 'Bob');

变量 name 现在可在所有视图中使用。所以你可以这样做

Flight::render('hello');

注意,在指定模板的名称时,可以在 render 方法中省略 .php 扩展名。

默认情况下,Flight 将在 views 目录中查找模板文件。你可以通过设置以下配置来为模板设置一个不同的路径

Flight::set('flight.views.path', '/path/to/views');

布局

对于网站来说,有一个单一的布局模板文件,其中包含可替换的内容是很常见的。要将内容渲染到布局中,你可以在 render 方法中传入一个可选参数。

Flight::render('header', array('heading' => 'Hello'), 'header_content');
Flight::render('body', array('body' => 'World'), 'body_content');

然后你的视图将保存名为 header_contentbody_content 的变量。然后你可以通过这样做来渲染布局

Flight::render('layout', array('title' => 'Home Page'));

如果模板文件看起来像这样

header.php:

<h1><?php echo $heading; ?></h1>

body.php:

<div><?php echo $body; ?></div>

layout.php:

<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $header_content; ?>
<?php echo $body_content; ?>
</body>
</html>

输出将是

<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Hello</h1>
<div>World</div>
</body>
</html>

自定义视图

Flight 允许您通过注册自己的视图类来简单地替换默认的视图引擎。以下是您如何使用 Smarty 模板引擎来处理视图

// Load Smarty library
require './Smarty/libs/Smarty.class.php';

// Register Smarty as the view class
// Also pass a callback function to configure Smarty on load
Flight::register('view', 'Smarty', array(), function($smarty){
    $smarty->template_dir = './templates/';
    $smarty->compile_dir = './templates_c/';
    $smarty->config_dir = './config/';
    $smarty->cache_dir = './cache/';
});

// Assign template data
Flight::view()->assign('name', 'Bob');

// Display the template
Flight::view()->display('hello.tpl');

为了完整性,您还应该覆盖 Flight 的默认渲染方法

Flight::map('render', function($template, $data){
    Flight::view()->assign($data);
    Flight::view()->display($template);
});

错误处理

错误和异常

所有错误和异常都被 Flight 捕获,并传递给 error 方法。默认行为是发送一个包含一些错误信息的通用 HTTP 500 内部服务器错误 响应。

您可以根据自己的需求覆盖此行为

Flight::map('error', function(Exception $ex){
    // Handle error
    echo $ex->getTraceAsString();
});

默认情况下,错误不会记录到 Web 服务器。您可以通过更改配置来启用此功能

Flight::set('flight.log_errors', true);

未找到

当无法找到 URL 时,Flight 会调用 notFound 方法。默认行为是发送一个包含简单信息的 HTTP 404 未找到 响应。

您可以根据自己的需求覆盖此行为

Flight::map('notFound', function(){
    // Handle not found
});

重定向

您可以使用 redirect 方法并通过传递新 URL 来重定向当前请求

Flight::redirect('/new/location');

请求

Flight 将 HTTP 请求封装到一个单独的对象中,可以通过以下方式访问

$request = Flight::request();

请求对象提供了以下属性

url - The URL being requested
base - The parent subdirectory of the URL
method - The request method (GET, POST, PUT, DELETE)
referrer - The referrer URL
ip - IP address of the client
ajax - Whether the request is an AJAX request
scheme - The server protocol (http, https)
user_agent - Browser information
body - Raw data from the request body
type - The content type
length - The content length
query - Query string parameters
data - Post parameters
cookies - Cookie parameters
files - Uploaded files

您可以将 querydatacookiesfiles 属性作为数组或对象访问。

因此,要获取查询字符串参数,您可以这样做

$id = Flight::request()->query['id'];

或者您也可以这样做

$id = Flight::request()->query->id;

HTTP 缓存

Flight 提供了内置的 HTTP 级缓存支持。如果满足缓存条件,Flight 将返回一个 HTTP 304 未修改 响应。下次客户端请求相同的资源时,他们将被提示使用本地缓存的版本。

Last-Modified

您可以使用 lastModified 方法并传递一个 UNIX 时间戳来设置页面最后修改的日期和时间。客户端将继续使用他们的缓存,直到最后修改的值更改。

Flight::route('/news', function(){
    Flight::lastModified(1234567890);
    echo 'This content will be cached.';
});

ETag

ETag 缓存与 Last-Modified 类似,但您可以为资源指定任何想要的标识符

Flight::route('/news', function(){
    Flight::etag('my-unique-id');
    echo 'This content will be cached.';
});

请注意,调用 lastModifiedetag 都会设置和检查缓存值。如果请求之间的缓存值相同,Flight 将立即发送一个 HTTP 304 响应并停止处理。

停止

您可以通过调用 halt 方法在任何点停止框架

Flight::halt();

您还可以指定可选的 HTTP 状态代码和消息

Flight::halt(200, 'Be right back...');

调用 halt 将丢弃到该点为止的所有响应内容。如果您想停止框架并输出当前响应,请使用 stop 方法

Flight::stop();

配置

您可以通过设置配置值来自定义 Flight 的某些行为。

Flight::set('flight.log_errors', true);

以下是一个所有可用配置设置的列表。

flight.base_url - Override the base url of the request. (default: null)
flight.handle_errors - Allow Flight to handle all errors internally. (default: true)
flight.log_errors - Log errors to the web server's error log file. (default: false)
flight.views.path - Directory containing view template files (default: ./views)

框架方法

Flight 被设计成易于使用和理解。以下是框架的完整方法集。它由核心方法组成,这些是常规静态方法,以及可扩展的方法,这些是映射方法,可以进行过滤或覆盖。

核心方法

Flight::map($name, $callback) // Creates a custom framework method.
Flight::register($name, $class, [$params], [$callback]) // Registers a class to a framework method.
Flight::before($name, $callback) // Adds a filter before a framework method.
Flight::after($name, $callback) // Adds a filter after a framework method.
Flight::path($path) // Adds a path for autoloading classes.
Flight::get($key) // Gets a variable.
Flight::set($key, $value) // Sets a variable.
Flight::has($key) // Checks if a variable is set.
Flight::clear([$key]) // Clears a variable.
Flight::init() // Initializes the framework to its default settings.

可扩展方法

Flight::start() // Starts the framework.
Flight::stop() // Stops the framework and sends a response.
Flight::halt([$code], [$message]) // Stop the framework with an optional status code and message.
Flight::route($pattern, $callback) // Maps a URL pattern to a callback.
Flight::redirect($url, [$code]) // Redirects to another URL.
Flight::render($file, [$data], [$key]) // Renders a template file.
Flight::error($exception) // Sends an HTTP 500 response.
Flight::notFound() // Sends an HTTP 404 response.
Flight::etag($id, [$type]) // Performs ETag HTTP caching.
Flight::lastModified($time) // Performs last modified HTTP caching.
Flight::json($data) // Sends a JSON response.

通过 mapregister 添加的任何自定义方法也可以进行过滤。

框架实例

您可以选择将 Flight 作为对象实例而不是全局静态类来运行。

require 'flight/autoload.php';

use flight\Engine;

$app = new Engine();

$app->route('/', function(){
    echo 'hello world!';
});

$app->start();

因此,您可以通过调用 Engine 对象上具有相同名称的实例方法来调用静态方法。