More refactoring, updated documenation

pull/11/head
Mike Cao 13 years ago
parent e2f1dc99bb
commit 5d789ceb2e

@ -1,7 +1,7 @@
# Flight
# What is Flight?
Flight is a fast, simple, and extensible framework for PHP.
It allows you to quickly build RESTful web applications with minimal effort:
Flight is a fast, simple, extensible framework for PHP.
Flight enables you to quickly and easily build RESTful web applications.
require 'flight/Flight.php';
@ -11,21 +11,30 @@ It allows you to quickly build RESTful web applications with minimal effort:
Flight::start();
[Learn more](http://flightphp.com/learn)
## Installation
# Requirements
1\. Download and extract the Flight framework files to your web directory.
Flight requires PHP 5.3 or greater.
# License
Flight is released under the [MIT](http://www.opensource.org/licenses/mit-license.php) license.
# Installation
1\. [Download](https://github.com/mikecao/flight/tarball/master) and extract the Flight framework files to your web directory.
2\. Configure your webserver.
For **Apache**, edit your `.htaccess` file with the following:
For *Apache*, edit your .htaccess file with the following:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
For **Nginx**, add the following to your server declaration:
For *Nginx*, add the following to your server declaration:
server {
location / {
@ -33,7 +42,7 @@ For **Nginx**, add the following to your server declaration:
}
}
3\. Create your `index.php` file.
3\. Create your index.php file.
First include the framework.
@ -49,10 +58,7 @@ Finally, start the framework.
Flight::start();
## Routing
### The Basics
# Routing
Routing in Flight is done by matching a URL pattern with a callback function.
@ -65,6 +71,7 @@ The callback can be any object that is callable. So you can use a regular functi
function hello(){
echo 'hello world!';
}
Flight::route('/', 'hello');
Or a class method:
@ -74,11 +81,12 @@ Or a class method:
echo 'hello world!';
}
}
Flight::route('/', array('Greeting','hello'));
Routes are matched in the order they are defined. The first route to match a request is invoked.
Routes are matched in the order they are defined. The first route to match a request will be invoked.
### Method Routing
## Method Routing
By default, route patterns are matched against all request methods. You can respond to specific
methods by placing an identifier before the URL.
@ -86,6 +94,7 @@ methods by placing an identifier before the URL.
Flight::route('GET /', function(){
echo 'I received a GET request.';
});
Flight::route('POST /', function(){
echo 'I received a POST request.';
});
@ -98,7 +107,7 @@ You can also map multiple methods to a single callback by using a `|` delimiter:
Method specific routes have precedence over global routes.
### Regular Expressions
## Regular Expressions
You can use regular expressions in your routes:
@ -106,15 +115,9 @@ You can use regular expressions in your routes:
// This will match /user/1234
});
You can also use the wildcard character `*` for matching:
## Named Parameters
Flight::route('/blog/*', function(){
// This will match /blog/2000/02/01
});
### Named Parameters
You can specify named parameters in routes which will be passed along to your callback function.
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)!";
@ -127,15 +130,25 @@ You can also include regular expressions with your named parameters by using the
// But will not match /bob/12345
});
Note that named parameters only match URL segments. If you want to match multiple segments use the `*` wildcard.
## Wildcards
Matching is only done on individual URL segments. If you want to match multiple segments you can use the `*` wildcard.
## Extending
Flight::route('/blog/*', function(){
// This will match /blog/2000/02/01
});
Flight is an extensible framework. Flight's features are individual components that can extended or overridden.
You can map your own methods, register your own classes, or even override existing classes and methods.
To route all requests to a single callback, you can do:
### Mapping Methods
Flight::route('*', function(){
// Do something
});
# Extending
Flight 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:
@ -147,7 +160,7 @@ To map your own custom method, you use the `map` function:
// Call your custom method
Flight::hello('Bob');
### Registering Classes
## Registering Classes
To register your own class, you use the `register` function:
@ -157,10 +170,7 @@ To register your own class, you use the `register` function:
// Get an instance of your class
$user = Flight::user();
If the `User` class is not defined, Flight will look in it's local folder for a file called `User.php` and autoload it.
This is how Flight loads its default classes like Response, Request, and Router.
You can define the constructor parameters for your class by passing in an additional array:
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:
// Register class with constructor parameters
Flight::register('db', 'Database', array('localhost','mydb','user','pass'));
@ -172,7 +182,7 @@ You can define the constructor parameters for your class by passing in an additi
//
$db = Flight::db();
You can also define a callback that will be executed immediately after class construction.
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.
// The callback will be passed the object that was constructed
Flight::register('db', 'Database', array('localhost', 'mydb', 'user', 'pass'), function($db){
@ -180,7 +190,7 @@ You can also define a callback that will be executed immediately after class con
});
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:
To get a new instance of a class, simply pass in `false` as a parameter:
// Shared instance of User
$shared = Flight::user();
@ -189,15 +199,14 @@ To get a new instance of a class, simply pass in *false* as a parameter:
$new = Flight::user(false);
Keep in mind that mapped methods have precedence over registered classes. If you declare both
for the same method name, only the mapped method will be invoked.
using the same name, only the mapped method will be invoked.
## Overriding
# Overriding
Flight ships with lots of default functionality to help you get your started.
However, you can override these features to suit your needs without having to modify any code.
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 HTTP 404 response.
You can override this method to handle 404 errors however you like by mapping over it:
You can override this behavior by using the `map` method:
Flight::map('notFound', function(){
// Display custom 404 page
@ -211,7 +220,7 @@ Flight also has custom error handling which you can override:
log_error($e);
});
Flight also allows you to replace core components if you want.
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:
// Register your custom class
@ -220,43 +229,38 @@ For example you can replace the default Router class with your own custom class:
// When Flight loads the Router instance, it will load your class
$myrouter = Flight::router();
You can replace any of the default Flight components:
Framework methods like `map` and `register` however cannot be overridden. You will get an error if you try to do so.
Flight::request();
Flight::response();
Flight::router();
Flight::view();
# Filtering
However, core framework methods like `map` and `register` cannot be overridden.
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:
## Method Filtering
function(&$params, &$output) {
// Filter code
}
Flight allows you to filter methods before and after they are called. There are no predefined hooks
you need to memorize. You can simply filter any method Flight invokes, including custom methods that
you've mapped.
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){
Flight::before('start', function(&$params, &$output){
// Do something
});
You can have a filter run after a method by doing:
Flight::after('start', function(&$output){
Flight::after('start', function(&$params, &$output){
// Do something
});
You can add as many filters as you want to any method. They will be called in the order
that they are declared.
Notice that the filter callbacks have arguments passed to them. All *before* filters
are passed an array of the method parameters. All *after* filters are passed the output of
the method being filtered. The arguments are passed by reference so your filter simply needs
to modify the contents.
Here's an example the filtering process:
Here's an example of the filtering process:
// Map a custom method
Flight::map('hello', function($name){
@ -264,44 +268,46 @@ Here's an example the filtering process:
});
// Add a before filter
Flight::before('hello', function(&$params){
Flight::before('hello', function(&$params, &$output){
// Manipulate the parameter
$params[0] = strtoupper($params[0]);
$params[0] = 'Fred';
});
// Add an after filter
Flight::after('hello', function(&$output){
Flight::after('hello', function(&$params, &$output){
// Manipulate the output
$output .= " Have a nice day!";
}
// Invoke the custom method
echo Flight::hello('bob');
echo Flight::hello('Bob');
This should display:
Hello BOB! Have a nice day!
Hello Fred! Have a nice day!
### Framework Methods
If you have defined multiple filters, you can break the chain by returning `false`:
You can apply filters to any of these existing framework methods:
Flight::before('start', function(&$params, &$output){
echo 'one';
});
start
stop
route
halt
error
notFound
redirect
render
etag
lastModified
Flight::before('start', function(&$params, &$output){
echo 'two';
Core framework methods like `map` and `register` however cannot be filtered because they are called
directly and not invoked dynamically.
// This will end the chain
return false;
});
// This will not get called
Flight::before('start', function(&$params, &$output){
echo 'three';
});
## Variables
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.
@ -313,7 +319,7 @@ Flight allows you to save variables so that they can be used anywhere in your ap
To see if a variable has been set you can do:
if (Flight::exists('id')) {
if (Flight::has('id')) {
// Do something
}
@ -327,71 +333,91 @@ You can clear a variable by doing:
Flight also uses variables for configuration purposes.
Flight::set('flight.lib.path', '/path/to/library');
Flight::set('flight.log_errors', true);
# Views
## Views
Flight provides some basic templating functionality by default. To display a view call the `render` method with the
name of the template file and optional template data:
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:
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, <?php echo $name; ?>!
Hello, '<?php echo $name; ?>'!
The output would be:
Hello, Bob!
You can manually set view variables at any time by using the `set` method:
You can also manually set view variables by using the set method:
Flight::view()->set('name', 'Bob');
Set variables will be automatically be included when you render a view. So you can simply do:
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.
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:
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
## Layouts
It is common for websites to have a single layout template file with interchanging content. To render content for a layout you need to pass in a variable name to the `render` method.
Flight::render('header', array('heading' => 'Hello'), 'header_content');
Flight::render('body', array('message' => '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' => 'Home');
If the template file looks like this:
It is common to have a single layout template file with interchanging content. To render content for a layout you need
to pass in a variable name to the render method.
header.php:
Flight::render('hello', array('name' => 'Bob'), 'body_content');
<h1><?php echo $heading; ?></h1>
Your view will have a saved variable called `body_content`. You can then render your layout by doing:
body.php:
Flight::render('layout');
<div><?php echo $body; ?></div>
Your layout template file could look like this:
layout.php:
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $header_content; ?>
<?php echo $body_content; ?>
</body>
</html>
### Custom Views
The output would be:
<html>
<head>
<title>My Page</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:
Here's how you would use the [Smarty](http://www.smarty.net/) template engine for your views:
// Load Smarty library
require './Smarty/libs/Smarty.class.php';
// Register Smarty as the view class and pass
// a callback function to configure Smarty on load
// 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/';
@ -412,35 +438,44 @@ For completeness, you should also override Flight's default render method:
Flight::view()->display($template);
});
# Error Handling
## Error Handling
### Errors and Exceptions
## Errors and Exceptions
All errors and exceptions are caught by Flight and passed to the `error` method.
The default behavior is to send an HTTP `500 Internal Server Error` response with some error information.
You can override this behavior for your own needs.
The default behavior is to send a generic HTTP `500 Internal Server Error` response with some error information.
You can override this behavior for your own needs:
Flight::map('error', function(){
// Handle error
});
### Not Found
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 HTTP `404 Not Found` response with a simple message. You can override this behavior for your own needs.
send an HTTP `404 Not Found` response with a simple message. You can override this behavior for your own needs:
Flight::map('notFound', function(){
// Display custom error page
});
## Redirects
# Redirects
You can redirect the current request by using the `redirect` method and passing in a new URL:
Flight::redirect('/new/location');
## HTTP Caching
# HTTP Caching
Flight provides built-in support for HTTP level caching. If the caching condition is met,
Flight will return an HTTP `304 Not Modified` response. The next time the client requests the same resource,
they will be prompted to use their locally cached version.
### Last-Modified
## 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.
@ -450,7 +485,7 @@ The client will continue to use their cache until the last modified value is cha
echo 'This content will be cached.';
});
### ETag
## ETag
ETag caching is similar to Last-Modified, except you can specify any id you want for the resource:
@ -463,8 +498,7 @@ Keep in mind that calling either `lastModified` or `etag` will both set and chec
If the cache value is the same between requests, Flight will immediately send the `304` response and stop
processing.
## Stopping
# Stopping
You can stop the framework at any point by calling the `halt` method:
@ -478,13 +512,3 @@ 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();
## Requirements
Flight requires PHP 5.3 or later.
## License
Flight is licensed under the [MIT](http://www.opensource.org/licenses/mit-license.php) license.

@ -200,13 +200,16 @@ class Flight {
self::$loader = new \flight\core\Loader();
self::$dispatcher = new \flight\core\Dispatcher();
// Register default components
// Initialize autoloading
self::$loader->init();
self::$loader->addDirectory(dirname(__DIR__));
// Register default components
self::$loader->register('request', '\flight\net\Request');
self::$loader->register('response', '\flight\net\Response');
self::$loader->register('router', '\flight\net\Router');
self::$loader->register('view', '\flight\template\View', array(), function($view){
$view->path = Flight::get('flight.views.path') ?: './views';
$view->path = Flight::get('flight.views.path');
});
// Register framework methods
@ -214,11 +217,14 @@ class Flight {
'start','stop','route','halt','error','notFound',
'render','redirect','etag','lastModified','json'
);
foreach ($methods as $name) {
self::$dispatcher->set($name, array(__CLASS__, '_'.$name));
}
// Default settings
self::set('flight.views.path', './views');
self::set('flight.log_errors', false);
// Enable output buffering
ob_start();
@ -255,13 +261,16 @@ class Flight {
* Starts the framework.
*/
public static function _start() {
$router = self::router();
$request = self::request();
// Route the request
$callback = self::router()->route(self::request());
$callback = $router->route($request);
if ($callback !== false) {
self::$dispatcher->execute(
$callback,
array_values(self::request()->params)
array_values($router->params)
);
}
else {
@ -269,7 +278,7 @@ class Flight {
}
// Disable caching for AJAX requests
if (self::request()->ajax) {
if ($request->ajax) {
self::response()->cache(false);
}
@ -316,6 +325,9 @@ class Flight {
* @param object $ex Exception
*/
public static function _error(Exception $e) {
if (self::get('flight.log_errors')) {
error_log($e->getMessage());
}
self::response(false)
->status(500)
->write(

@ -11,7 +11,7 @@ namespace flight\core;
/**
* The Dispatcher class is responsible for dispatching events. Events
* are simply aliases for class methods or functions. The Dispatcher
* allows you to hook other function to an event that can modify the
* allows you to hook other functions to an event that can modify the
* input parameters and/or the output.
*/
class Dispatcher {
@ -29,8 +29,6 @@ class Dispatcher {
*/
protected $filters = array();
public function __construct() {}
/**
* Dispatches an event.
*
@ -42,7 +40,7 @@ class Dispatcher {
// Run pre-filters
if (!empty($this->filters[$name]['before'])) {
$this->filter($this->filters[$name]['before'], $params, $output);
$this->filter($this->filters[$name]['before'], $params, null);
}
// Run requested method
@ -76,6 +74,33 @@ class Dispatcher {
return $this->events[$name];
}
/**
* Checks if an event has been set.
*
* @param string $name Event name
* @return bool Event status
*/
public function has($name) {
return isset($this->events[$name]);
}
/**
* Clears an event. If no name is given,
* all events are removed.
*
* @param string $name Event name
*/
public function clear($name = null) {
if ($name !== null) {
unset($this->events[$name]);
unset($this->filters[$name]);
}
else {
$this->events = array();
$this->filters = array();
}
}
/**
* Hooks a callback to an event.
*
@ -91,7 +116,8 @@ class Dispatcher {
* Executes a chain of method filters.
*
* @param array $filters Chain of filters
* @param reference $data Method parameters or method output
* @param reference $params Method parameters
* @param reference $output Method output
*/
public function filter($filters, &$params, &$output) {
$args = array(&$params, &$output);

@ -36,13 +36,6 @@ class Loader {
*/
protected $dirs = array();
/**
* Constructor. Enables autoloading.
*/
public function __construct() {
spl_autoload_register(array(__CLASS__, 'autoload'));
}
/**
* Registers a class.
*
@ -140,10 +133,30 @@ class Loader {
/**
* Adds a directory for autoloading classes.
*
* @param string $dir Directory path
* @param mixed $dir Directory path
*/
public function addDirectory($dir) {
$this->dirs[] = $dir;
if (is_array($dir) || is_object($dir)) {
foreach ($dir as $value) {
$this->dirs[] = $value;
}
}
else if (is_string($dir)) {
$this->dirs[] = $dir;
}
}
/**
* Initializes the autoloader.
*/
public function init() {
static $initialized = false;
if (!$initialized) {
spl_autoload_register(array(__CLASS__, 'autoload'));
$initialized = true;
}
}
/**

@ -29,8 +29,6 @@ namespace flight\net;
* data - Post parameters
* cookies - Cookie parameters
* files - Uploaded files
* params - Matched URL parameters from the router
* matched - Matched URL patter from the router
*/
class Request {
/**
@ -53,12 +51,10 @@ class Request {
'body' => file_get_contents('php://input'),
'type' => $_SERVER['CONTENT_TYPE'],
'length' => $_SERVER['CONTENT_LENGTH'],
'query' => (object)$_GET,
'data' => (object)$_POST,
'cookies' => (object)$_COOKIE,
'files' => (object)$_FILES,
'params' => array(),
'matched' => null
'query' => $_GET,
'data' => $_POST,
'cookies' => $_COOKIE,
'files' => $_FILES
);
}
@ -83,9 +79,8 @@ class Request {
$this->url = '/';
}
else {
$query = self::parseQuery($this->url);
$this->query = (object)$query;
$_GET = $query;
$this->query = self::parseQuery($this->url);
$_GET = $this->query;
}
}

@ -21,6 +21,20 @@ class Router {
*/
protected $routes = array();
/**
* Matched route.
*
* @var string
*/
public $matched = null;
/**
* Matched URL parameters.
*
* @var array
*/
public $params = array();
/**
* Gets mapped routes.
*
@ -60,9 +74,9 @@ class Router {
* Tries to match a requst to a route. Also parses named parameters in the url.
*
* @param string $pattern URL pattern
* @param object $request Request object
* @param string $url Requested URL
*/
public function match($pattern, $request) {
public function match($pattern, $url) {
$ids = array();
// Build the regex for matching
@ -83,12 +97,12 @@ class Router {
)).'\/?(?:\?.*)?$/i';
// Attempt to match route and named parameters
if (preg_match($regex, $request->url, $matches)) {
if (preg_match($regex, $url, $matches)) {
if (!empty($ids)) {
$request->params = array_intersect_key($matches, $ids);
$this->params = array_intersect_key($matches, $ids);
}
$request->matched = $pattern;
$this->matched = $pattern;
return true;
}
@ -103,13 +117,13 @@ class Router {
* @return callable Matched callback function
*/
public function route(Request $request) {
$request->matched = null;
$request->params = array();
$this->matched = null;
$this->params = array();
$routes = ($this->routes[$request->method] ?: array()) + ($this->routes['*'] ?: array());
foreach ($routes as $pattern => $callback) {
if ($pattern === '*' || $request->url === $pattern || self::match($pattern, $request)) {
if ($pattern === '*' || $request->url === $pattern || self::match($pattern, $request->url)) {
return $callback;
}
}

@ -71,7 +71,7 @@ class View {
* @param string $key Key
*/
public function has($key) {
return !isset($this->data[$key]);
return isset($this->data[$key]);
}
/**

Loading…
Cancel
Save