Vous êtes sur la page 1sur 13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

Flight
An extensible micro-framework for PHP
about

install

learn

code

User Guide
Routing
Extending
Overriding
Filtering
Variables
Views
Error Handling
Redirects
Requests
HTTP Caching
JSON
Configuration
Framework Methods

Routing
Routing in Flight is done by matching a URL pattern with a callback function.
Flight::route('/',function(){
echo'helloworld!';
});

The callback can be any object that is callable. So you can use a regular function:
functionhello(){
echo'helloworld!';
}
Flight::route('/','hello');

Or a class method:
classGreeting{
publicstaticfunctionhello(){
echo'helloworld!';
}
}
Flight::route('/',array('Greeting','hello'));

Routes are matched in the order they are defined. The first route to match a request will be invoked.

Method Routing
http://flightphp.com/learn#routing

1/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

By default, route patterns are matched against all request methods. You can respond to specific methods by
placing an identifier before the URL.
Flight::route('GET/',function(){
echo'IreceivedaGETrequest.';
});
Flight::route('POST/',function(){
echo'IreceivedaPOSTrequest.';
});

You can also map multiple methods to a single callback by using a | delimiter:
Flight::route('GET|POST/',function(){
echo'IreceivedeitheraGEToraPOSTrequest.';
});

Regular Expressions
You can use regular expressions in your routes:
Flight::route('/user/[09]+',function(){
//Thiswillmatch/user/1234
});

Named Parameters
You can specify named parameters in your routes which will be passed along to your callback function.
Flight::route('/@name/@id',function($name,$id){
echo"hello,$name($id)!";
});

You can also include regular expressions with your named parameters by using the : delimiter:
Flight::route('/@name/@id:[09]{3}',function($name,$id){
//Thiswillmatch/bob/123
//Butwillnotmatch/bob/12345
});

Optional Parameters
You can specify named parameters that are optional for matching by wrapping segments in parentheses.
Flight::route('/blog(/@year(/@month(/@day)))',function($year,$month,$day){
//ThiswillmatchthefollowingURLS:
///blog/2012/12/10
///blog/2012/12
///blog/2012
///blog
});

Any optional parameters that are not matched will be passed in as NULL.

Wildcards
Matching is only done on individual URL segments. If you want to match multiple segments you can use the *
wildcard.
http://flightphp.com/learn#routing

2/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

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

To route all requests to a single callback, you can do:


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

Passing
You can pass execution on to the next matching route by returning true from your callback function.
Flight::route('/user/@name',function($name){
//Checksomecondition
if($name!="Bob"){
//Continuetonextroute
returntrue;
}
});
Flight::route('/user/*',function(){
//Thiswillgetcalled
});

Route Info
If you want to inspect the matching route information, you can request for the route object to be passed to
your callback by passing in true as the third parameter in the route method. The route object will always be
the last parameter passed to your callback function.
Flight::route('/',function($route){
//ArrayofHTTPmethodsmatchedagainst
$route>methods;
//Arrayofnamedparameters
$route>params;
//Matchingregularexpression
$route>regex;
//Containsthecontentsofany'*'usedintheURLpattern
$route>splat;
},true);

Extending
Flight is designed to be an extensible framework. The framework comes with a set of default methods and
components, but it allows you to map your own methods, register your own classes, or even override
existing classes and methods.

Mapping Methods
To map your own custom method, you use the map function:
//Mapyourmethod
Flight::map('hello',function($name){
echo"hello$name!";
});
http://flightphp.com/learn#routing

3/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

//Callyourcustommethod
Flight::hello('Bob');

Registering Classes
To register your own class, you use the register function:
//Registeryourclass
Flight::register('user','User');
//Getaninstanceofyourclass
$user=Flight::user();

The register method also allows you to pass along parameters to your class constructor. So when you load
your custom class, it will come pre-initialized. You can define the constructor parameters by passing in an
additional array. Here's an example of loading a database connection:
//Registerclasswithconstructorparameters
Flight::register('db','PDO',array('mysql:host=localhost;dnbname=test','user','pass'));
//Getaninstanceofyourclass
//Thiswillcreateanobjectwiththedefinedparameters
//
//newPDO('mysql:host=localhost;dnbname=test','user','pass');
//
$db=Flight::db();

If you pass in an additional callback parameter, it will be executed immediately after class construction. This
allows you to perform any set up procedures for your new object. The callback function takes one
parameter, an instance of the new object.
//Thecallbackwillbepassedtheobjectthatwasconstructed
Flight::register('db','PDO',array('mysql:host=localhost;dnbname=test','user','pass'),function($db){
$db>setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
});

By default, every time you load your class you will get a shared instance. To get a new instance of a class,
simply pass in false as a parameter:
//Sharedinstanceoftheclass
$shared=Flight::db();
//Newinstanceoftheclass
$new=Flight::db(false);

Keep in mind that mapped methods have precedence over registered classes. If you declare both using the
same name, only the mapped method will be invoked.

Overriding
Flight allows you to override its default functionality to suit your own needs, without having to modify any
code.
For example, when Flight cannot match a URL to a route, it invokes the notFound method which sends a
generic HTTP404 response. You can override this behavior by using the map method:
Flight::map('notFound',function(){
//Displaycustom404page
http://flightphp.com/learn#routing

4/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

include'errors/404.html';
});

Flight also allows you to replace core components of the framework. For example you can replace the
default Router class with your own custom class:
//Registeryourcustomclass
Flight::register('router','MyRouter');
//WhenFlightloadstheRouterinstance,itwillloadyourclass
$myrouter=Flight::router();

Framework methods like map and register however cannot be overridden. You will get an error if you try to
do so.

Filtering
Flight allows you to filter methods before and after they are called. There are no predefined hooks you need
to memorize. You can filter any of the default framework methods as well as any custom methods that
you've mapped.
A filter function looks like this:
function(&$params,&$output){
//Filtercode
}

Using the passed in variables you can manipulate the input parameters and/or the output.
You can have a filter run before a method by doing:
Flight::before('start',function(&$params,&$output){
//Dosomething
});

You can have a filter run after a method by doing:


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

You can add as many filters as you want to any method. They will be called in the order that they are
declared.
Here's an example of the filtering process:
//Mapacustommethod
Flight::map('hello',function($name){
return"Hello,$name!";
});
//Addabeforefilter
Flight::before('hello',function(&$params,&$output){
//Manipulatetheparameter
$params[0]='Fred';
});
//Addanafterfilter
http://flightphp.com/learn#routing

5/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

Flight::after('hello',function(&$params,&$output){
//Manipulatetheoutput
$output.="Haveaniceday!";
}
//Invokethecustommethod
echoFlight::hello('Bob');

This should display:


HelloFred!Haveaniceday!

If you have defined multiple filters, you can break the chain by returning false in any of your filter functions:
Flight::before('start',function(&$params,&$output){
echo'one';
});
Flight::before('start',function(&$params,&$output){
echo'two';
//Thiswillendthechain
returnfalse;
});
//Thiswillnotgetcalled
Flight::before('start',function(&$params,&$output){
echo'three';
});

Note, core methods such as map and register cannot be filtered because they are called directly and not
invoked dynamically.

Variables
Flight allows you to save variables so that they can be used anywhere in your application.
//Saveyourvariable
Flight::set('id',123);
//Elsewhereinyourapplication
$id=Flight::get('id');

To see if a variable has been set you can do:


if(Flight::has('id')){
//Dosomething
}

You can clear a variable by doing:


//Clearstheidvariable
Flight::clear('id');
//Clearsallvariables
Flight::clear();

Flight also uses variables for configuration purposes.

http://flightphp.com/learn#routing

6/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

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

Views
Flight provides some basic templating functionality by default. To display a view template call the render
method with the name of the template file and optional template data:
Flight::render('hello.php',array('name'=>'Bob'));

The template data you pass in is automatically injected into the template and can be reference like a local
variable. Template files are simply PHP files. If the content of the hello.php template file is:
Hello,'<?phpecho$name;?>'!

The output would be:


Hello,Bob!

You can also manually set view variables by using the set method:
Flight::view()>set('name','Bob');

The variable name is now available across all your views. So you can simply do:
Flight::render('hello');

Note that when specifying the name of the template in the render method, you can leave out the .php
extension.
By default Flight will look for a views directory for template files. You can set an alternate path for your
templates by setting the following config:
Flight::set('flight.views.path','/path/to/views');

Layouts
It is common for websites to have a single layout template file with interchanging content. To render content
to be used in a layout, you can pass in an optional parameter to the render method.
Flight::render('header',array('heading'=>'Hello'),'header_content');
Flight::render('body',array('body'=>'World'),'body_content');

Your view will then have saved variables called header_content and body_content. You can then render
your layout by doing:
Flight::render('layout',array('title'=>'HomePage'));

If the template files looks like this:


header.php:
http://flightphp.com/learn#routing

7/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

<h1><?phpecho$heading;?></h1>

body.php:
<div><?phpecho$body;?></div>

layout.php:
<html>
<head>
<title><?phpecho$title;?></title>
</head>
<body>
<?phpecho$header_content;?>
<?phpecho$body_content;?>
</body>
</html>

The output would be:


<html>
<head>
<title>HomePage</title>
</head>
<body>
<h1>Hello</h1>
<div>World</div>
</body>
</html>

Custom Views
Flight allows you to swap out the default view engine simply by registering your own view class. Here's how
you would use the Smarty template engine for your views:
//LoadSmartylibrary
require'./Smarty/libs/Smarty.class.php';
//RegisterSmartyastheviewclass
//AlsopassacallbackfunctiontoconfigureSmartyonload
Flight::register('view','Smarty',array(),function($smarty){
$smarty>template_dir='./templates/';
$smarty>compile_dir='./templates_c/';
$smarty>config_dir='./config/';
$smarty>cache_dir='./cache/';
});
//Assigntemplatedata
Flight::view()>assign('name','Bob');
//Displaythetemplate
Flight::view()>display('hello.tpl');

For completeness, you should also override Flight's default render method:
Flight::map('render',function($template,$data){
Flight::view()>assign($data);
Flight::view()>display($template);
});

http://flightphp.com/learn#routing

8/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

Error Handling
Errors and Exceptions
All errors and exceptions are caught by Flight and passed to the error method. The default behavior is to
send a generic HTTP500InternalServerError response with some error information.
You can override this behavior for your own needs:
Flight::map('error',function(Exception$ex){
//Handleerror
echo$ex>getTraceAsString();
});

By default errors are not logged to the web server. You can enable this by changing the config:
Flight::set('flight.log_errors',true);

Not Found
When a URL can't be found, Flight calls the notFound method. The default behavior is to send an HTTP404
NotFound response with a simple message.
You can override this behavior for your own needs:
Flight::map('notFound',function(){
//Handlenotfound
});

Redirects
You can redirect the current request by using the redirect method and passing in a new URL:
Flight::redirect('/new/location');

By default Flight sends a HTTP 303 status code. You can optionally set a custom code:
Flight::redirect('/new/location',401);

Requests
Flight encapsulates the HTTP request into a single object, which can be accessed by doing:
$request=Flight::request();

The request object provides the following properties:


urlTheURLbeingrequested
baseTheparentsubdirectoryoftheURL
methodTherequestmethod(GET,POST,PUT,DELETE)
referrerThereferrerURL
ipIPaddressoftheclient
http://flightphp.com/learn#routing

9/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

ajaxWhethertherequestisanAJAXrequest
schemeTheserverprotocol(http,https)
user_agentBrowserinformation
typeThecontenttype
lengthThecontentlength
queryQuerystringparameters
dataPostdataorJSONdata
cookiesCookieparameters
filesUploadedfiles
secureWhethertheconnectionissecure
acceptHTTPacceptparameters
proxy_ipProxyIPaddressoftheclient

You can access the query, data, cookies, and files properties as arrays or objects.
So, to get a query string parameter, you can do:
$id=Flight::request()>query['id'];

Or you can do:


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

RAW Request Body


To get the raw HTTP request body, for example when dealing with PUT requests, you can do:
$body=Flight::request()>getBody();

JSON Input
If you send request with the type application/json and the data {"id":123} it will be availabe from the
data property:
$id=Flight::request()>data>id;

HTTP Caching
Flight provides built-in support for HTTP level caching. If the caching condition is met, Flight will return an
HTTP 304NotModified response. The next time the client requests the same resource, they will be
prompted to use their locally cached version.

Last-Modified
You can use the lastModified method and pass in a UNIX timestamp to set the date and time a page was
last modified. The client will continue to use their cache until the last modified value is changed.
Flight::route('/news',function(){
Flight::lastModified(1234567890);
echo'Thiscontentwillbecached.';
});

ETag
ETag caching is similar to LastModified, except you can specify any id you want for the resource:

http://flightphp.com/learn#routing

10/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

Flight::route('/news',function(){
Flight::etag('myuniqueid');
echo'Thiscontentwillbecached.';
});

Keep in mind that calling either lastModified or etag will both set and check the cache value. If the cache
value is the same between requests, Flight will immediately send an HTTP304 response and stop processing.

Stopping
You can stop the framework at any point by calling the halt method:
Flight::halt();

You can also specify an optional HTTP status code and message:
Flight::halt(200,'Berightback...');

Calling halt will discard any response content up to that point. If you want to stop the framework and output
the current response, use the stop method:
Flight::stop();

JSON
Flight provides support for sending JSON and JSONP responses. To send a JSON response you pass some
data to be JSON encoded:
Flight::json(array('id'=>123));

For JSONP requests you would use the jsonp method. You can optionally pass in the query parameter name
you are using to define your callback function:
Flight::jsonp(array('id'=>123),'q');

So, when making a GET request using ?q=my_func, you should receive the output:
my_func({"id":123});

If you don't pass in a query parameter name it will default to jsonp.

Configuration
You can customize certain behaviors of Flight by setting configuration values through the set method.
Flight::set('flight.log_errors',true);

The following is a list of all the available configuration settings.

http://flightphp.com/learn#routing

11/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP

flight.base_urlOverridethebaseurloftherequest.(default:null)
flight.handle_errorsAllowFlighttohandleallerrorsinternally.(default:true)
flight.log_errorsLogerrorstothewebserver'serrorlogfile.(default:false)
flight.views.pathDirectorycontainingviewtemplatefiles(default:./views)

Framework Methods
Flight is designed to be easy to use and understand. The following is the complete set of methods for the
framework. It consists of core methods, which are regular static methods, and extensible methods, which
can be filtered or overridden.

Core Methods
Flight::map($name,$callback)//Createsacustomframeworkmethod.
Flight::register($name,$class,[$params],[$callback])//Registersaclasstoaframeworkmethod.
Flight::before($name,$callback)//Addsafilterbeforeaframeworkmethod.
Flight::after($name,$callback)//Addsafilterafteraframeworkmethod.
Flight::path($path)//Addsapathforautoloadingclasses.
Flight::get($key)//Getsavariable.
Flight::set($key,$value)//Setsavariable.
Flight::has($key)//Checksifavariableisset.
Flight::clear([$key])//Clearsavariable.

Extensible Methods
Flight::start()//Startstheframework.
Flight::stop()//Stopstheframeworkandsendsaresponse.
Flight::halt([$code],[$message])//Stoptheframeworkwithanoptionalstatuscodeandmessage.
Flight::route($pattern,$callback)//MapsaURLpatterntoacallback.
Flight::redirect($url,[$code])//RedirectstoanotherURL.
Flight::render($file,[$data],[$key])//Rendersatemplatefile.
Flight::error($exception)//SendsanHTTP500response.
Flight::notFound()//SendsanHTTP404response.
Flight::etag($id,[$type])//PerformsETagHTTPcaching.
Flight::lastModified($time)//PerformslastmodifiedHTTPcaching.
Flight::json($data,[$code],[$encode])//SendsaJSONresponse.
Flight::jsonp($data,[$param],[$code],[$encode])//SendsaJSONPresponse.

Any custom methods added with map and register can also be filtered.

Framework Instance
Instead of running Flight as a global static class, you can optionally run it as an object instance.
require'flight/autoload.php';
useflight\Engine;
$app=newEngine();
$app>route('/',function(){
echo'helloworld!';
});
$app>start();

All of the existing static methods are available as regular class methods.

http://flightphp.com/learn#routing

12/13

8/30/2015

FlightAnextensiblemicroframeworkforPHP
Copyright 2011-2015 Mike Cao
Powered by Flight

http://flightphp.com/learn#routing

13/13

Vous aimerez peut-être aussi