@ -141,6 +167,7 @@ You can specify named parameters that are optional for matching by wrapping segm
// /blog/2012
// /blog/2012
// /blog
// /blog
});
});
```
Any optional parameters that are not matched will be passed in as NULL.
Any optional parameters that are not matched will be passed in as NULL.
@ -148,15 +175,19 @@ Any optional parameters that are not matched will be passed in as NULL.
Matching is only done on individual URL segments. If you want to match multiple segments you can use the `*` wildcard.
Matching is only done on individual URL segments. If you want to match multiple segments you can use the `*` wildcard.
```php
Flight::route('/blog/*', function(){
Flight::route('/blog/*', function(){
// This will match /blog/2000/02/01
// This will match /blog/2000/02/01
});
});
```
To route all requests to a single callback, you can do:
To route all requests to a single callback, you can do:
```php
Flight::route('*', function(){
Flight::route('*', function(){
// Do something
// Do something
});
});
```
# Extending
# Extending
@ -166,6 +197,7 @@ Flight is designed to be an extensible framework. The framework comes with a set
To map your own custom method, you use the `map` function:
To map your own custom method, you use the `map` function:
```php
// Map your method
// Map your method
Flight::map('hello', function($name){
Flight::map('hello', function($name){
echo "hello $name!";
echo "hello $name!";
@ -173,19 +205,23 @@ To map your own custom method, you use the `map` function:
// Call your custom method
// Call your custom method
Flight::hello('Bob');
Flight::hello('Bob');
```
## Registering Classes
## Registering Classes
To register your own class, you use the `register` function:
To register your own class, you use the `register` function:
```php
// Register your class
// Register your class
Flight::register('user', 'User');
Flight::register('user', 'User');
// Get an instance of your class
// Get an instance of your class
$user = Flight::user();
$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:
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:
@ -195,80 +231,92 @@ The register method also allows you to pass along parameters to your class const
// new Database('localhost', 'mydb', 'user', 'pass');
// new Database('localhost', 'mydb', 'user', 'pass');
//
//
$db = Flight::db();
$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.
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.
```php
// The callback will be passed the object that was constructed
// The callback will be passed the object that was constructed
By default, every time you load your class you will get a shared instance.
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:
```php
// Shared instance of Database class
// Shared instance of Database class
$shared = Flight::db();
$shared = Flight::db();
// New instance of Database class
// New instance of Database class
$new = Flight::db(false);
$new = Flight::db(false);
```
Keep in mind that mapped methods have precedence over registered classes. If you declare both
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.
using the same name, only the mapped method will be invoked.
# Overriding
# Overriding
Flight allows you to override its default functionality to suit your own 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.
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 behavior by using the `map` method:
You can override this behavior by using the `map` method:
```php
Flight::map('notFound', function(){
Flight::map('notFound', function(){
// Display custom 404 page
// Display custom 404 page
include 'errors/404.html';
include 'errors/404.html';
});
});
```
Flight also allows you to replace core components of the framework.
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:
For example you can replace the default Router class with your own custom class:
```php
// Register your custom class
// Register your custom class
Flight::register('router', 'MyRouter');
Flight::register('router', 'MyRouter');
// When Flight loads the Router instance, it will load your class
// When Flight loads the Router instance, it will load your class
$myrouter = Flight::router();
$myrouter = Flight::router();
```
Framework methods like `map` and `register` however cannot be overridden. You will get an error if you try to do so.
Framework methods like `map` and `register` however cannot be overridden. You will get an error if you try to do so.
# Filtering
# Filtering
Flight allows you to filter methods before and after they are called. There are no predefined hooks
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.
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:
A filter function looks like this:
```php
function(&$params, &$output) {
function(&$params, &$output) {
// Filter code
// Filter code
}
}
```
Using the passed in variables you can manipulate the input parameters and/or the output.
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:
You can have a filter run before a method by doing:
Note, core methods such as `map` and `register` cannot be filtered because they are called
Note, core methods such as `map` and `register` cannot be filtered because they are called directly and not invoked dynamically.
directly and not invoked dynamically.
# Variables
# Variables
Flight allows you to save variables so that they can be used anywhere in your application.
Flight allows you to save variables so that they can be used anywhere in your application.
```php
// Save your variable
// Save your variable
Flight::set('id', 123);
Flight::set('id', 123);
// Elsewhere in your application
// Elsewhere in your application
$id = Flight::get('id');
$id = Flight::get('id');
```
To see if a variable has been set you can do:
To see if a variable has been set you can do:
```php
if (Flight::has('id')) {
if (Flight::has('id')) {
// Do something
// Do something
}
}
```
You can clear a variable by doing:
You can clear a variable by doing:
```php
// Clears the id variable
// Clears the id variable
Flight::clear('id');
Flight::clear('id');
// Clears all variables
// Clears all variables
Flight::clear();
Flight::clear();
```
Flight also uses variables for configuration purposes.
Flight also uses variables for configuration purposes.
```php
Flight::set('flight.log_errors', true);
Flight::set('flight.log_errors', true);
```
# Views
# 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 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:
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:
```php
Hello, '<?php echo $name; ?>'!
Hello, '<?php echo $name; ?>'!
```
The output would be:
The output would be:
@ -358,41 +419,56 @@ The output would be:
You can also manually set view variables by using the set method:
You can also manually set view variables by using the set method:
```php
Flight::view()->set('name', 'Bob');
Flight::view()->set('name', 'Bob');
```
The variable `name` is now available across all your views. So you can simply do:
The variable `name` is now available across all your views. So you can simply do:
```php
Flight::render('hello');
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:
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.
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 allows you to swap out the default view engine simply by registering your own view class.
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](http://www.smarty.net/) template engine for your views:
Here's how you would use the [Smarty](http://www.smarty.net/) template engine for your views:
```php
// Load Smarty library
// Load Smarty library
require './Smarty/libs/Smarty.class.php';
require './Smarty/libs/Smarty.class.php';
@ -437,53 +515,68 @@ Here's how you would use the [Smarty](http://www.smarty.net/) template engine fo
// Display the template
// Display the template
Flight::view()->display('hello.tpl');
Flight::view()->display('hello.tpl');
```
For completeness, you should also override Flight's default render method:
For completeness, you should also override Flight's default render method:
```php
Flight::map('render', function($template, $data){
Flight::map('render', function($template, $data){
Flight::view()->assign($data);
Flight::view()->assign($data);
Flight::view()->display($template);
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.
All errors and exceptions are caught by Flight and passed to the `error` method.
The default behavior is to send a generic HTTP `500 Internal Server Error` response with some error information.
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:
You can override this behavior for your own needs:
```php
Flight::map('error', function(){
Flight::map('error', function(){
// Handle error
// Handle error
});
});
```
By default errors are not logged to the web server. You can enable this by changing the config:
By default errors are not logged to the web server. You can enable this by changing the config:
```php
Flight::set('flight.log_errors', true);
Flight::set('flight.log_errors', true);
```
## Not Found
## Not Found
When a URL can't be found, Flight calls the `notFound` method. The default behavior is to
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.
send an HTTP `404 Not Found` response with a simple message. You can override this behavior for your own needs:
You can override this behavior for your own needs:
```php
Flight::map('notFound', function(){
Flight::map('notFound', function(){
// Handle not found
// Handle not found
});
});
```
# Redirects
# Redirects
You can redirect the current request by using the `redirect` method and passing in a new URL:
You can redirect the current request by using the `redirect` method and passing in a new URL:
```php
Flight::redirect('/new/location');
Flight::redirect('/new/location');
```
# Requests
# Requests
Flight encapsulates the HTTP request into a single object, which can be accessed by doing:
Flight encapsulates the HTTP request into a single object, which can be accessed by doing:
```php
$request = Flight::request();
$request = Flight::request();
```
The request object provides the following properties:
The request object provides the following properties:
```
url - The URL being requested
url - The URL being requested
base - The parent subdirectory of the URL
base - The parent subdirectory of the URL
method - The request method (GET, POST, PUT, DELETE)
method - The request method (GET, POST, PUT, DELETE)
@ -499,109 +592,102 @@ The request object provides the following properties:
data - Post parameters
data - Post parameters
cookies - Cookie parameters
cookies - Cookie parameters
files - Uploaded files
files - Uploaded files
```
You can access the `query`, `data`, `cookies`, and `files` properties as arrays or objects.
You can access the `query`, `data`, `cookies`, and `files` properties as arrays or objects.
So, to get a query string parameter, you can do:
So, to get a query string parameter, you can do:
```php
$id = Flight::request()->query['id'];
$id = Flight::request()->query['id'];
```
Or you can do:
Or you can do:
```php
$id = Flight::request()->query->id;
$id = Flight::request()->query->id;
```
# HTTP Caching
# HTTP Caching
Flight provides built-in support for HTTP level caching. If the caching condition is met,
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.
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.
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.
The client will continue to use their cache until the last modified value is changed.
```php
Flight::route('/news', function(){
Flight::route('/news', function(){
Flight::lastModified(1234567890);
Flight::lastModified(1234567890);
echo 'This content will be cached.';
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:
`ETag` caching is similar to `Last-Modified`, except you can specify any id you want for the resource:
```php
Flight::route('/news', function(){
Flight::route('/news', function(){
Flight::etag('my-unique-id');
Flight::etag('my-unique-id');
echo 'This content will be cached.';
echo 'This content will be cached.';
});
});
```
Keep in mind that calling either `lastModified` or `etag` will both set and check the cache value.
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 `HTTP 304` response and stop processing.
If the cache value is the same between requests, Flight will immediately send an HTTP 304 response and stop
processing.
# Stopping
# Stopping
You can stop the framework at any point by calling the `halt` method:
You can stop the framework at any point by calling the `halt` method:
```php
Flight::halt();
Flight::halt();
```
You can also specify an optional HTTP status code and message:
You can also specify an optional `HTTP` status code and message:
```php
Flight::halt(200, 'Be right back...');
Flight::halt(200, 'Be right back...');
```
Calling `halt` will discard any response content up to that point.
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:
If you want to stop the framework and output the current response, use the `stop` method:
```php
Flight::stop();
Flight::stop();
```
# Framework Methods
# Framework Methods
Flight is designed to be easy to use and understand. The following is the complete set of 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.
for the framework. It consists of core methods, which are regular static methods, and
extensible methods, which can be filtered or overridden.
## Core Methods
## Core Methods
Flight::map($name, $callback) - Creates a custom framework method.
```php
Flight::map($name, $callback) // Creates a custom framework method.
Flight::register($name, $class, [$params], [$callback]) - Registers a class to a 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::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::after($name, $callback) - Adds a filter after a framework method.
Flight::get($key) // Gets a variable.
Flight::set($key, $value) // Sets a variable.
Flight::path($path) - Adds a path for autoloading classes.
Flight::has($key) // Checks if a variable is set.
Flight::clear([$key]) // Clears a variable.
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.
## Extensible Methods
## Extensible Methods
Flight::start() - Starts the framework.
```php
Flight::start() // Starts the framework.
Flight::stop() - Stops the framework and sends a response.
Flight::stop() // Stops the framework and sends a response.
Flight::halt([$code], [$message]) // Stop the framework with an optional status code and message.
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::route($pattern, $callback) - Maps a URL pattern to a callback.
Flight::render($file, [$data], [$key]) // Renders a template file.
Flight::error($exception) // Sends an HTTP 500 response.
Flight::redirect($url, [$code]) - Redirects to another URL.