unikent/flight

此包已被弃用且不再维护。没有建议的替代包。

Flight 是一个快速、简单、可扩展的 PHP 框架。Flight 允许您快速轻松地构建 RESTful 网络应用程序。这为肯特大学网络开发团队所需的原始代码添加了一些小的改进。

维护者

详细信息

github.com/unikent/flight

源代码

安装: 648

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 12

分支: 273

dev-master 2013-02-20 12:14 UTC

This package is not auto-updated.

Last update: 2016-11-19 06:57:46 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
});

扩展

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 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!

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

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的默认render方法

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

错误处理

错误和异常

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

您可以覆盖此行为以满足自己的需求

Flight::map('error', function(){
    // Handle error
});

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

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

未找到

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

您可以覆盖此行为以满足自己的需求

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 Not Modified响应。下次客户端请求相同资源时,它们将被提示使用本地缓存的版本。

Last-Modified

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

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

ETag

ETag 缓存类似于 Last-Modified,不同之处在于你可以为资源指定任何你想要的 ID

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::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::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 400 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 添加的任何自定义方法也可以被筛选。