Home  >  Article  >  Backend Development  >  Flight

Flight

WBOY
WBOYOriginal
2016-08-08 09:29:062402browse

Instructions: Flight official website & Original text

What is Flight? Flight is a fast, simple, extensible PHP framework. Flight enables you to create RESTful web applications quickly and easily. require'flight/Flight.php';Flight::route('/', function(){echo'hello world!';});Flight::start();Learn moreRequirementsFlight requires PHP 5.3or higher. LicenseFlight is released under the MIT license.Installation1. After downloading, take out the Flight framework file and put it in your web directory. 2. Configure your web serverFor the Apache server, edit your .htaccess file as follows: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [QSA,L] For the Nginx server, add the following to your server declaration: server { location / { try_files $uri $uri/ /index.php; } } 3 . Create your index.php fileThe first step is to introduce this framework. require'flight/Flight.php';Then define a route and register a function to handle the request. Flight::route('/', function(){echo'hello world!';});Finally, launch the framework. Flight::start();RoutingRouting in Flight is to match a URL pattern to a callback function. Flight::route('/', function(){echo'hello world!';});The callback function can be any target that can be called. So you can use a regular function: functionhello(){echo'hello world!';}Flight::route('/', 'hello'); or a method in a class: classGreeting {publicstaticfunctionhello() {echo'hello world!'; }}Flight::route('/', array('Greeting','hello'));Routes are matched in the order in which they are defined. The first route that matches the request will be called. (HTTP) method routingBy default, routing patterns can match all request methods. You can respond to a specific method by prepending a method identifier to the 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(){// 这个将匹配到 /user/1234});命名参数你可以在路由中指定命名参数,它们会被传递到你的回调函数里。Flight::route('/@name/@id', function($name, $id){echo"hello, $name ($id)!";});你也可以通过使用:分隔符在命名变量中引入正则表达式Flight::route('/@name/@id:[0-9]{3}', function($name, $id){// 这个将匹配到 /bob/123// 但是不会匹配到 /bob/12345});可选参数你可以通过将URL段(segments)包在括号里的方式来指定哪些命名参数是可选的。Flight::route('/blog(/@year(/@month(/@day)))', function($year, $month, $day){// 它将匹配如下URLS:// /blog/2012/12/10// /blog/2012/12// /blog/2012// /blog});任何没有被匹配到的可选参数将以NULL值传入。通配符匹配只发生在单独的URL段(segments)。如果你想匹配多段,可以使用*通配符。Flight::route('/blog/*', function(){// 这个将匹配到 /blog/2000/02/01});要将所有的请求路由到单一的回调上,你可以这么做:Flight::route('*', function(){// Do something});路由的传递当从一个被匹配到的回调函数中返回true时,路由功能将继续执行,传递到下一个能匹配的路由中。Flight::route('/user/@name', function($name){// 检查某些条件if ($name!="Bob") {// 延续到下一个路由returntrue; }});Flight::route('/user/*', function(){// 这里会被调用到});路由信息如果你想检视匹配到的路由信息,可以请求将路由对象传递到你的回调函数中:你需要把 route方法的第三个参数设置成true。这个路由对象总是会作为最后一个参数传入你的回调函数。Flight::route('/', function($route){// 匹配到的HTTP方法的数组$route->methods;// 命名参数数组$route->params;// 匹配的正则表达式$route->regex;// Contains the contents of any '*' used in the URL pattern$route->splat;}, true);扩展Fligth被设计成一个可扩展的框架。这个框架带来了一系列的默认方法和组件,但是它允许你 映射你自己的方法,注册你自己的类,甚至可以重写已有的类和方法。方法的映射你可以使用map函数去映射你自定义的方法:// 映射你自己的方法Flight::map('hello', function($name){echo"hello $name!";});// 调用你的自定义方法Flight::hello('Bob');类的注册你可以使用register函数去注册你自己的类:// 注册你定义的类Flight::register('user', 'User');// 得到你定义的类的一个实例$user=Flight::user();register方法允许你向类的构造函数传递参数。所以当你加载自定义类的时候,它将会 预初始化(pre-initialized)。你可以通过一个追加的数组来传递定义的构造函数参数。 这是一个加载数据库连接的例子:// 注册一个带有构造函数参数的类Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'));// 得到你定义的类的一个实例// 这里将创建一个带有你定义的参数的对象//// new PDO('mysql:host=localhost;dbname=test','user','pass');//$db=Flight::db();如果你传递了额外的回调函数参数,它将会在类构造完之后立即执行。这就允许你为这个新对象去 执行任何的安装过程(set up procedures)。这个回调函数会被传递一个参数,就是这个新对象的实例。// 这个回调函数将会传递到这个被构造的对象中Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'), function($db){$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);});默认情况下,每次你加载一个类,你会得到一个共享的实例。如果要得到一个类的新实例, 简单的传递一个false参数就行了。// 类的共享实例$shared=Flight::db();// 类的新实例$new=Flight::db(false);需要记住的是,被映射的方法优先于被注册的类。如果你用相同的名字将它们都声明了,那么只有 映射的方法会被调用。重写(Overriding)Flight允许你按照自己的需要去重写它的默认功能,而不用修改任何框架的代码。例如,当Flight的路由功能没有匹配到一个URL时,它会调用notFound方法,发出一个通用的 HTTP 404响应。你可以使用map方法去重写这个行为。Flight::map('notFound', function(){// 显示自定义的404页面include'errors/404.html';});Flight也允许你替换这个框架的核心组件。例如你可以将默认的Router类替换成你自定义的类:// 注册成你自定义的类Flight::register('router', 'MyRouter');// When Flight loads the Router instance, it will load your class// 当Flight加载Router实例时,将会加载到你自定义的类$myrouter=Flight::router();然而框架的方法诸如map和register是不能够被重写的。如果你尝试这么做的话你会得到一个error。过滤Flight允许你在方法调用之前和之后去过滤它。框架里没有任何你需要记住的预定义的钩子。你可以 过滤任何被映射的自定义方法和框架中的方法。一个过滤器函数是像这样的:function(&$params, &$output) {// Filter code}通过传入的变量,你可以操作输入参数和/或输出参数。这样做就可以在一个方法运行之前运行一个过滤器:Flight::before('start', function(&$params, &$output){// Do something});这样做就可以在一个方法运行之后运行一个过滤器:Flight::after('start', function(&$params, &$output){// Do something});你可以给任何函数添加任意数量的过滤器。它们将按照声明的顺序依次被调用。这里是一个过滤器处理的例子:// 映射一个自定义的方法Flight::map('hello', function($name){return"Hello, $name!";});// 添加一个前置的过滤器Flight::before('hello', function(&$params, &$output){// 操作这里的params$params[0] ='Fred';});// 添加一个后置的过滤器Flight::after('hello', function(&$params, &$output){// 操作这里的output$output.=" Have a nice day!";});// 调用这个自定义方法echoFlight::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';// 如下将会终止这个过滤器链returnfalse;});// 这里将不会得到调用Flight::before('start', function(&$params, &$output){echo'three';});记住,核心函数诸如map和register是不能够被过滤的,因为它们是被直接调用而非动态调用的。变量Flight允许你定义变量,使得它能在应用内的任何地方被使用。// 保存你定义的变量Flight::set('id', 123);// 在应用的其他地方使用$id=Flight::get('id');去检测一个变量是否被设置了可以这么做:if (Flight::has('id')) {// Do something}去清除一个变量你可以这么做:// 清除这个id变量Flight::clear('id');// 清除所有的变量Flight::clear();Flight框架使用变量的目的还包括了配置。Flight::set('flight.log_errors', true);视图Flight默认提供了一些基础的模板功能。调用带有模板文件和 可选的模板数据的render函数,去显示一个视图模板。Flight::render('hello.php', array('name'=>'Bob'));你传进来的模板数据,会被自动的注入到模板当中,并且可以像一个本地变量一样去引用。 模板文件就是简单的PHP文件。如果一个文件名为hello.php的模板文件的内容是这样的:Hello, ''!输出会是:Hello, Bob! 你可以使用set函数来手动的设置视图中的变量:Flight::view()->set('name', 'Bob');这个name 变量现在在你所有的视图中都是可用的了。所以就可以简化成这样了:Flight::render('hello');注意当你在render函数中指定模板名时,你可以去掉这个.php的扩展名。默认情况下Flight会在views目录下寻找模板文件。你可以通过如下配置的设定来为你的模板 设置另外一个路径。Flight::set('flight.views.path', '/path/to/views');布局(Layouts)对网站来说,拥有一个单独的可交换内容的布局(layout)模板文件是很常见的。要在布局中使用渲染的内容, 你可以给render函数传递一个可选的参数。Flight::render('header', array('heading'=>'Hello'), 'header_content');Flight::render('body', array('body'=>'World'), 'body_content');紧接着你的视图就有了命名为header_content和body_content的已保存的变量。接下来你就可以 这样渲染你的布局了:Flight::render('layout', array('title'=>'Home Page'));如果你的模板文件是这样的:header.php:<h1><?phpecho$heading; ?>h1>body.php:<div><?phpecho$body; ?>div>layout.php:<html><head><title><?phpecho$title; ?>title> head> <body> echo$header_content; ?>echo$body_content; ?> body> html>输出会是:<html> <head> <title>Home Pagetitle> head> <body> <h1>Helloh1> <div>Worlddiv> body> html>自定义视图Flight允许你替换默认的视图引擎,只需简单的注册你自己的视图类即可。这里展示的是在视图中 如何使用Smarty模板引擎:// 加载Smarty类库require'./Smarty/libs/Smarty.class.php';// 将Smarty注册成视图类// 同时传递一个回调函数,在加载过程中配置SmartyFlight::register('view', 'Smarty', array(), function($smarty){$smarty->template_dir='./templates/';$smarty->compile_dir='./templates_c/';$smarty->config_dir='./config/';$smarty->cache_dir='./cache/';});// 模板中数据的赋值Flight::view()->assign('name', 'Bob');// 显示这个模板Flight::view()->display('hello.tpl');出于完备性,你还应该重写Flight的默认render方法:Flight::map('render', function($template, $data){Flight::view()->assign($data);Flight::view()->display($template);});错误(Error)处理错误(Errors)和异常(Exceptions)所有的errors和exceptions都会被Flight捕获,然后传到error方法。该方法默认的行为是 发出一个带有错误信息的通用的HTTP 500 Internal Server Error响应。出于你自己的需要,你可以重写这个行为:Flight::map('error', function(Exception$ex){// 错误处理echo$ex->getTraceAsString();});默认情况下,错误(errors)是不会被记录日志到web服务器的。你可以通过改变配置来允许记录。Flight::set('flight.log_errors', true);Not Found当一个URL没有被找到时,Flight将会调用notFound方法。该方法默认的行为是 发出一个通用的HTTP 404 Not Found响应并带有简单的说明信息。出于你自己的需要,你可以重写这个行为:Flight::map('notFound', function(){// 处理not found});重定向(Redirects)你可以使用redirect方法将当前请求重定向到传入的新URL中。Flight::redirect('/new/location');默认情况下Flight会发出一个HTTP 303状态码。你可以选择设置一个自定义的状态码。Flight::redirect('/new/location', 401);请求Flight将HTTP请求封装到一个单独的对象中,你可以这样获取到它:$request=Flight::request();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 type - The content type length - The content length query - Query string parameters data - Post data or JSON data cookies - Cookie data files - Uploaded files secure - Whether the connection is secure accept - HTTP accept parameters proxy_ip - Proxy IP address of the client
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn