An extensible micro-framework for PHP

Overview

What is Flight?

Flight is a fast, simple, extensible framework for PHP. Flight enables you to quickly and easily build RESTful web applications.

require 'flight/Flight.php';

Flight::route('/', function(){
    echo 'hello world!';
});

Flight::start();

Learn more

Requirements

Flight requires PHP 5.3 or greater.

License

Flight is released under the MIT license.

Installation

1. Download the files.

If you're using Composer, you can run the following command:

composer require mikecao/flight

OR you can download them directly and extract them to your web directory.

2. Configure your webserver.

For Apache, edit your .htaccess file with the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

Note: If you need to use flight in a subdirectory add the line RewriteBase /subdir/ just after RewriteEngine On.

For Nginx, add the following to your server declaration:

server {
    location / {
        try_files $uri $uri/ /index.php;
    }
}

3. Create your index.php file.

First include the framework.

require 'flight/Flight.php';

If you're using Composer, run the autoloader instead.

require 'vendor/autoload.php';

Then define a route and assign a function to handle the request.

Flight::route('/', function(){
    echo 'hello world!';
});

Finally, start the framework.

Flight::start();

Routing

Routing in Flight is done by matching a URL pattern with a callback function.

Flight::route('/', function(){
    echo 'hello world!';
});

The callback can be any object that is callable. So you can use a regular function:

function hello(){
    echo 'hello world!';
}

Flight::route('/', 'hello');

Or a class method:

class Greeting {
    public static function hello() {
        echo 'hello world!';
    }
}

Flight::route('/', array('Greeting', 'hello'));

Or an object method:

class Greeting
{
    public function __construct() {
        $this->name = 'John Doe';
    }

    public function hello() {
        echo "Hello, {$this->name}!";
    }
}

$greeting = new Greeting();

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

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 'I received a GET request.';
});

Flight::route('POST /', function(){
    echo 'I received a POST request.';
});

You can also map multiple methods to a single callback by using a | delimiter:

Flight::route('GET|POST /', function(){
    echo 'I received either a GET or a POST request.';
});

Regular Expressions

You can use regular expressions in your routes:

Flight::route('/user/[0-9]+', function(){
    // This will match /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:[0-9]{3}', function($name, $id){
    // This will match /bob/123
    // But will not match /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){
    // This will match the following URLS:
    // /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.

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

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

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

Passing

You can pass execution on to the next matching route by returning true from your callback function.

Flight::route('/user/@name', function($name){
    // Check some condition
    if ($name != "Bob") {
        // Continue to next route
        return true;
    }
});

Flight::route('/user/*', function(){
    // This will get called
});

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){
    // Array of HTTP methods matched against
    $route->methods;

    // Array of named parameters
    $route->params;

    // Matching regular expression
    $route->regex;

    // Contains the contents of any '*' used in the URL pattern
    $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:

// Map your method
Flight::map('hello', function($name){
    echo "hello $name!";
});

// Call your custom method
Flight::hello('Bob');

Registering Classes

To register your own class, you use the register function:

// Register your class
Flight::register('user', 'User');

// Get an instance of your class
$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:

// Register class with constructor parameters
Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'));

// Get an instance of your class
// This will create an object with the defined parameters
//
//     new PDO('mysql:host=localhost;dbname=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.

// The callback will be passed the object that was constructed
Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=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:

// Shared instance of the class
$shared = Flight::db();

// New instance of the class
$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 HTTP 404 response. You can override this behavior by using the map method:

Flight::map('notFound', function(){
    // Display custom 404 page
    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:

// Register your custom class
Flight::register('router', 'MyRouter');

// When Flight loads the Router instance, it will load your class
$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) {
    // Filter code
}

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){
    // Do something
});

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

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.

Here's an example of the filtering process:

// 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');

This should display:

Hello Fred! Have a nice day!

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';

    // This will end the chain
    return false;
});

// This will not get called
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.

// Save your variable
Flight::set('id', 123);

// Elsewhere in your application
$id = Flight::get('id');

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

if (Flight::has('id')) {
     // Do something
}

You can clear a variable by doing:

// Clears the id variable
Flight::clear('id');

// Clears all variables
Flight::clear();

Flight also uses variables for configuration purposes.

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, '<?php echo $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' => 'Home Page'));

If the template files looks like this:

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>

The output would be:

<html>
<head>
<title>Home 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:

// 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');

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);
});

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 HTTP 500 Internal Server Error response with some error information.

You can override this behavior for your own needs:

Flight::map('error', function(Exception $ex){
    // Handle error
    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 HTTP 404 Not Found response with a simple message.

You can override this behavior for your own needs:

Flight::map('notFound', function(){
    // Handle not found
});

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:

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
host - The request host name

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 a request with the type application/json and the data {"id": 123} it will be available 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 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

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 'This content will be cached.';
});

ETag

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

Flight::route('/news', function(){
    Flight::etag('my-unique-id');
    echo 'This content will be cached.';
});

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.

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, 'Be right back...');

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, 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:

flight.base_url - Override the base url of the request. (default: null)
flight.case_sensitive - Case sensitive matching for URLs. (default: false)
flight.handle_errors - Allow Flight to handle all errors internally. (default: true)
flight.log_errors - Log errors to the web server's error log file. (default: false)
flight.views.path - Directory containing view template files. (default: ./views)
flight.views.extension - View template file extension. (default: .php)

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 are mapped methods that can be filtered or overridden.

Core Methods

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::init() // Initializes the framework to its default settings.
Flight::app() // Gets the application object instance

Extensible Methods

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 404 response.
Flight::etag($id, [$type]) // Performs ETag HTTP caching.
Flight::lastModified($time) // Performs last modified HTTP caching.
Flight::json($data, [$code], [$encode], [$charset], [$option]) // Sends a JSON response.
Flight::jsonp($data, [$param], [$code], [$encode], [$charset], [$option]) // Sends a JSONP response.

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';

use flight\Engine;

$app = new Engine();

$app->route('/', function(){
    echo 'hello world!';
});

$app->start();

So instead of calling the static method, you would call the instance method with the same name on the Engine object.

Comments
  • Status Code always 200

    Status Code always 200

    Hi everybody,

    I want to send a status code to client eg. 400, 404, etc. same as function http_response_code(). But Flight always returned 200. I've already tried Flight::response()->status(400) but it's still returned 200. I googled but found no way to do this. Could you please help me to do it?

    Thanks !

    opened by vic4key 25
  • Need

    Need "splat" or similar for wildcard match

    If I have a route like 'GET /api/content/*', and someone submits a URL like '/api/content/home/about', I want to be able to get the 'home/about' part in an function argument. It might work like this:

    Flight::route('GET /api/content/*', function($wildcard) { echo $wildcard; });

    The Ruby REST library Sinatra allows this:

    get '/say//to/' do

    matches /say/hello/to/world

    params[:splat] # => ["hello", "world"] end

    get '/download/.' do

    matches /download/path/to/file.xml

    params[:splat] # => ["path/to/file", "xml"] end

    opened by jamiekurtz 13
  • Flight is removing my custom error_handler

    Flight is removing my custom error_handler

    Because of this code below (in addition to using \Flight::set('flight.handle_errors', false);):

    public function handleErrors($enabled)
        {
            if ($enabled) {
                set_error_handler(array($this, 'handleError'));
                set_exception_handler(array($this, 'handleException'));
            }
            else {
                restore_error_handler();
                restore_exception_handler();
            }
        }
    

    Flight is removing my custom error_handler that I defined before calling Flight::start() (because it would have no sense to define it after this call)

    I could not override the Engine (at least I tried using Flight::register but it did not work). And I could not override Flight itself so that I could manually override the $engine property (which is set using self::$engine = new new \flight\Engine();), because the propery is private. Extending the whole \Flight class obviously causes disastrous damage.

    Also, using an "after start" callback is of no use because the error arises during start(), not after.

    I don't know what else to do, but I cannot have uncaught errors in my app :(

    The only option for me is to define my error_handler during the construct of my controller (called by the router), but ideally I'd rather define my error_handler at the very beginning of my application code.

    Thanks for any tips, or for replacing the above code with something like:

    public function handleErrors($enabled)
        {
            if ($enabled) {
                set_error_handler(array($this, 'handleError'));
                set_exception_handler(array($this, 'handleException'));
            }
            else {
                // do nothing
            }
        }
    

    (I don't know if it will cause other issues though, but at least it will not remove any previously set error_handler)

    Sincerely,

    opened by rkyoku 12
  • My __construct didn't work in my BaseController, why ?

    My __construct didn't work in my BaseController, why ?

    My __construct didn't work in my BaseController, why ?

    ` class BaseController { public static $_time; // 当前时间

        public function __construct()
        {
            echo 123123;
            self::$_time = time();
        }
    }
    

    `

    there is no echo....

    opened by kuange 12
  • Issue with <!DOCTYPE html> in multi level route

    Issue with in multi level route

    When using a route like /about or / or /contact - the page renders just find using bootstrap. However, when using a multi-level route like /projects/photos - bootstrap fails to render.

    Upon using the browser inspection tool (right click --> inspect in chrome) it shows that there are no errors for a single level route (/about). But for a multi level route there is an error and it highlights the '<' of the line. image image

    the way I am doing the routes is:

    Flight::route('*', array('Layout', 'buildLayout')); 
    class Layout{
        public static function buildLayout(){
          //> script / css includes
          Flight::render('head', array('whatis' => 'stuff inside head tag'), 'head_content');
    
          //> build nav bar
          Flight::render('nav', array('site_name' => 'Bootstrap Template'), 'nav_content');
    
          //> build page Data
          Flight::render('page', array('whatis' => 'dynamic page content'), 'page_content');
    
          //> build full layout
          Flight::render('layout', array('show_footer' => 'yes'));
        }
      }
    

    Does anyone have any thoughts as to what I may be doing wrong?

    opened by agodlydeciple 12
  • Regex doesn't work in optional routing parameters

    Regex doesn't work in optional routing parameters

    I've noticed that you can't put any regex filters in an optional parameter for routes. E.g.

    Flight::route('/@controller/@method(/@id:[0-9]+)', function($controller, $method, $id){
        ...
    });
    
    opened by jammesz 11
  • Simple controllers implementation for Flight

    Simple controllers implementation for Flight

    Hi,

    Have you thought about implementing simple controllers? I think flight is a good framework to implement small application, but the routing system is a little complicated to organize in something more complex...

    Im using flight in a project and created a fork that supports simple controllers.

    Controllers extends FlightController class, and has an array with the routes and methods. Later, the controller can be installed calling like this:

    Flight::controller('ClassController');

    My fork: https://github.com/Th3DarKZI0N/flight

    Maybe this could take a look!

    Sorry for my bad english!!

    Regards, Gabriel

    opened by ghost 10
  • Flight::request()->data based on content type

    Flight::request()->data based on content type

    Hi there,

    Have you ever considered to map Flight::request()->data key values based on request Content-Type.

    This feature is useful in RESTful APIs, it adds an abstraction in Flight::request()->data and developer no needs to worry about the content-type of request

    POST /api/user HTTP/1.1
    Accept: application/json
    Content-type: application/json
    Content-Length: 10
    
    {"id":100}
    
    $request = \flight\net\Request ();
    $request->data[id] == 100;
    

    or maybe with new class

    $request = \flight\net\RestRequest ();
    $request->data[id] == 100;
    

    I know that extending flight is so easy but I was wondering if you want to add it to flight's repo not.

    opened by slashmili 10
  • Flight, PHP and MySQL

    Flight, PHP and MySQL

    Unfortunately the documentation for Flight is rather lacking, and I'm unable to figure out how to properly query a MySQL database using Flight.

    <?php
    
    # Includes #
    require_once('flight/Flight.php');
    
    # Database Information #
    Flight::register('db', 'Database', array('localhost', 'database', 'username', 'password'));
    
    # Queries #
    Flight::route('/name/@name:[a-zA-Z]', function($name) {
            $db = Flight::db();
            $db->connect();
            return($db->query("SELECT * FROM active WHERE short_name LIKE '$name' LIMIT 0, 30"));
    });
    
    Flight::route('/address/@address:[a-zA-Z0-9]', function($address) {
            # mysql query using $address
    });
    
    ?>
    

    A preview of the database: database

    And this is what the script returns: return

    Anyone able to led some help?

    opened by zQueal 10
  • added workaround to load Request body only if needed

    added workaround to load Request body only if needed

    On every call routed by flightphp, the Request body will be read by the Request object (even if it is not used at all). This is very time (CPU cycles) and memory consuming if you use file upload or PUT requests as the whole data get loaded into memory in one chunk.

    Additional it is possible to crash the whole php application by only sending enough data as the request could not be parsed anymore.

    Added workaround to load body only if it's needed (and not loaded by the application itself).

    opened by smeinecke 9
  • Filter

    Filter "before" route method

    Hi,

    I'd like to check for HTTP method (get/post/delete/put/patch) and check for authentication. I thought this would work:

    Flight::before('route', function(&$params, &$output){
        // check for a method
    });
    

    but it doesn't work. Any suggestions?

    thanks, -- buriwoy

    opened by chapani 9
  • Uncaught TypeError: flight\Engine::_route(): Argument #2 ($callback) must be of type callable, array given

    Uncaught TypeError: flight\Engine::_route(): Argument #2 ($callback) must be of type callable, array given

    I'm trying to use a simple route, adapted from the docs, to route requests to / to a controller method, and I get errors on PHP 8.1. Works on 7.4:

    <?php
    
    use Trains\Controllers\Index;
    
    require __DIR__ . '/../vendor/autoload.php';
    
    Flight::route('/', [Index::class, 'index']);
    
    Flight::start();
    

    NOTICE: PHP message: PHP Fatal error: Uncaught TypeError: flight\Engine::_route(): Argument #2 ($callback) must be of type callable, array given, called in /application/vendor/mikecao/flight/flight/core/Dispatcher.php on line 227 and defined in /application/vendor/mikecao/flight/flight/Engine.php:443

    opened by mattfletcher 2
  • [Extension plan] Middleware / route filtering

    [Extension plan] Middleware / route filtering

    As there seems to be a decent amount of interest among Flight users (myself included) in implementing middleware / route filtering (#276, #350), I decided to write some experimental code today.

    As @mikecao has made clear that he's not interested in adding this kind of code to the main flight library, this draft code is written as an extension.

    I'm going to publish a least one version to packagist, but not until I've studied proper PSR implementation. Pretty sure I would have to write some adapter for some of Flight's classes (no biggy).

    If anyone's interested in providing advice, requests, etc, let me know.

    Minimal example:

    <?PHP // -*- mode: web -*-
    
    use Paxperscientiam\FlightRoutesFilter\FlightRouteFilterBuilder;
    
    require "../vendor/autoload.php";
    
    Flight::map("authRequired", function () {
        echo "authRequired filter applied<br><br>";
        exit;
    });
    
    Flight::map("derp", function () {
        echo "derp filter applied<br><br>";
    });
    
    Flight::map("greetAbe", function () {
        echo "Hi Abe!<br><br>";
    });
    
    $x = new FlightRouteFilterBuilder(Flight::app());
    
    $x
        ->addBeforeFilter("/a", "derp")
        ->addBeforeFilter("/a", "authRequired")
        ->addBeforeFilter("/abe", "greetAbe")
        ->build();
    
    Flight::route('/other', function () use ($x) {
        s($x->getFilters()['applied']);
        echo 'rendered';
    });
    
    Flight::route('/abe', function () use ($x) {
        s($x->getFilters()['applied']);
        echo 'rendered';
    });
    
    Flight::route('/a', function () use ($x) {
        echo 'glad to be authorized';
    });
    
    Flight::map('error', function (Exception $ex) {
        echo $ex->getTraceAsString();
    });
    
    Flight::start();
    

    Code as of now: https://github.com/paxperscientiam/flight-routes-filter/tree/v0.0.2

    opened by paxperscientiam 0
  • Flight::path() problem

    Flight::path() problem

    Hi, i'm trying to make it work on nginx, and just want to understand what im doing wrong

    So, here is my nginx cfg where i put try_files from your Installation guide:

    server {
            listen 80 default_server;
            listen [::]:80 default_server;
    
            root /var/www/phpmvc.loc;
            index index.php index.html index.htm index.nginx-debian.html;
            server_name phpmvc.loc;
    
            location / {
                    try_files $uri $uri/ /index.php;
            }
    
            location ~ \.php$ {
                    include snippets/fastcgi-php.conf;
                    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
            }
    
            location ~ /\.ht {
                    deny all;
            }
       error_log /var/log/nginx/project_error.log;
       access_log /var/log/nginx/project_access.log;
    }
    

    Im using composer so there is how my index.php looked like:

    <?php
      error_reporting(E_ALL);
      ini_set('display_errors', '1');
    
      include dirname(__FILE__) . '/vendor/autoload.php';
    
      Flight::path(__DIR__ . '/controllers');
    
      include dirname(__FILE__) . '/routes.php';
    
      Flight::start();
    

    And this is my routes.php:

    <?php
    Flight::route('/', array('MainController', 'index'));
    

    And in this case i have an error all the time in Flight version 1.3

    500 Internal Server Error
    Invalid callback specified. (0)
    #0 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/Engine.php(322): flight\core\Dispatcher::execute()
    #1 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(196): flight\Engine->_start()
    #2 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(142): flight\core\Dispatcher::invokeMethod()
    #3 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(48): flight\core\Dispatcher::execute()
    #4 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/Engine.php(65): flight\core\Dispatcher->run()
    #5 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(196): flight\Engine->__call()
    #6 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/Flight.php(77): flight\core\Dispatcher::invokeMethod()
    #7 /var/www/phpmvc.loc/index.php(32): Flight::__callStatic()
    #8 {main}
    

    And this error in current 2.0.1

    Fatal error: Uncaught TypeError: Argument 2 passed to flight\Engine::_route() must be callable, array given, called in /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php on line 227 and defined in /var/www/phpmvc.loc/vendor/mikecao/flight/flight/Engine.php:443 Stack trace: #0 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(227): flight\Engine->_route() #1 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(162): flight\core\Dispatcher::invokeMethod() #2 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(54): flight\core\Dispatcher::execute() #3 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/Engine.php(98): flight\core\Dispatcher->run() #4 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/core/Dispatcher.php(227): flight\Engine->__call() #5 /var/www/phpmvc.loc/vendor/mikecao/flight/flight/Flight.php(97): flight\core\Dispatcher::invokeMethod() #6 /var/www/phpmvc.loc/routes.php(16): Flight::__callStatic() #7 /var/www/phpmvc.loc/index.php(24): include( in /var/www/phpmvc.loc/vendor/mikecao/flight/flight/Engine.php on line 443
    

    And i made it work only when im include my MainController.php directrly in index.php include dirname(__FILE__) . '/controllers/MainController.php'; and then i added use namespace\MainController.php in routes.php and made an object

    $controller = new MainController();
    Flight::route('/', array($controller, 'index'));
    

    After this manipulations its worked, but i want to use Flight::path What i am doing wrong here?

    opened by AndrewSikorsky 1
  • Route not working

    Route not working

    This URl is not picked up by the below Flight::route, it returns 404 route not found:

    http://localhost/api/intune/hey?error=access_denied&error_description=AADSTS65004%3a+User+declined+to+consent+to+access+the+app.%0d%0aTrace+ID%3a+747c0cc1-ccbd-4e53-8e2f-48812eb24100%0d%0aCorrelation+ID%3a+362e3cb3-20ef-400b-904e-9983bd989184%0d%0aTimestamp%3a+2022-09-08+09%3a58%3a12Z&error_uri=https%3a%2f%2flogin.microsoftonline.com%2ferror%3fcode%3d65004&admin_consent=True&state=x2EUE0fcSj#

    This URL IS picked up by the below Flight::Route: http://localhost/api/intune/hey?error=access_denied&error_uri=https%3a%2f%2flogin.microsoftonline.com%2ferror%3fcode%3d65004&admin_consent=True&state=x2EUE0fcSj#

    It looks like something in the query parameter error_description is causing flight not to pick up this route.

    If you have any ideas I'd appreciate it :)

    Flight::route('GET /api/intune/hey', function () { die("hey"); });

    opened by SeanPatten 2
  • Routes other than `/` don't work

    Routes other than `/` don't work

    Hi! this is my index.php file:

    <?php
    require 'vendor/autoload.php';
    
    Flight::route("/atu" , function(){
    	echo "HI";
    });
    Flight::route('/', function(){
        echo 'hello world!';
    });
    
    
    Flight::start();
    

    and this is my .htaccess file:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [QSA,L]
    

    and this is what i get when i try to access localhost/atu: image

    Where's the problem?!

    Update: I just tested it on a server and it works fine, but i cant use it on my local machine.

    opened by ehsanghorbani190 2
  • multiple words route

    multiple words route

    hello, How can I allow multiple words in a route?

    //domain.com/detroit //domain.com/new-york $city='detroit|miami|new-york|boston'; F::route('/('.$city.')', function(){ ... });

    opened by oscarlosan 1
Framework X – the simple and fast micro framework for building reactive web applications that run anywhere.

Framework X Framework X – the simple and fast micro framework for building reactive web applications that run anywhere. Quickstart Documentation Tests

Christian Lück 620 Jan 7, 2023
Framework for building extensible server-side progressive applications for modern PHP.

Chevere ?? Subscribe to the newsletter to don't miss any update regarding Chevere. Framework for building extensible server-side progressive applicati

Chevere 65 Jan 6, 2023
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Slim Framework Slim is a PHP micro-framework that helps you quickly write simple yet powerful web applications and APIs. Installation It's recommended

Slim Framework 11.5k Jan 4, 2023
A tiny, yet powerful, PHP micro-framework.

Equip Framework A tiny and powerful PHP micro-framework created and maintained by the engineering team at When I Work. Attempts to be PSR-1, PSR-2, PS

Equip 118 Jun 24, 2022
A resource-oriented micro PHP framework

Bullet Bullet is a resource-oriented micro PHP framework built around HTTP URIs. Bullet takes a unique functional-style approach to URL routing by par

Vance Lucas 415 Dec 27, 2022
A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast! Condensed in a single ~65KB file

Bong Cosca 2.6k Dec 30, 2022
a micro mvc framework for php

micro-mvc-php a micro mvc framework for php Config your Web url in .env . lifecycle All request proccess by index.php Autoload files include in bootst

Amiranbari 6 Jul 9, 2022
Lite & fast micro PHP framework that is **easy to learn**.

Utopia Framework is a PHP MVC based framework with minimal must-have features for professional, simple, advanced and secure web development.

utopia 139 Dec 30, 2022
The Slim PHP micro framework paired with Laravel's Illuminate Database toolkit.

Slim & Eloquent The Slim PHP micro framework paired with Laravel's Illuminate Database toolkit. Getting started # Download composer curl -s https://ge

Kyle Ladd 111 Jul 23, 2022
⚡ Micro API using Phalcon Framework

Micro App (Rest API) ⚡ Micro API using Phalcon PHP Framework. PHPDocs I. Requirements A Laptop ?? Docker (docker-compose*) Makefile (cli) II. Installa

Neutrapp 7 Aug 6, 2021
Mutexes for Micro-Framework HLEB

Use of mutexes in a project (including projects based on the HLEB micro framework) The use of mutexes is worthwhile in cases, when access to any code

Foma Tuturov 1 Oct 11, 2022
A curated list of awesome tutorials and other resources for the Slim micro framework

Awesome Slim A curated list of awesome tutorials and other resources for the Slim micro framework Table of Contents Essentials Tutorials Packages and

Sawyer Charles 466 Dec 8, 2022
Plates Template Integration for Slim micro framework 3

Plates Template Integration for Slim micro framework 3 Render your Slim 3 application views using Plates template engine. Install Via Composer $ compo

Projek XYZ 26 Feb 5, 2022
BEdita, ready to use back-end API, extensible API-first Content Management

BEdita, a back-end API BEdita 4 is a ready to use back-end API to handle the data of your mobile, IoT, web and desktop applications. It's also an exte

BEdita 65 Oct 31, 2022
Lite & fast micro PHP abuse library that is **easy to use**.

Utopia Abuse Utopia framework abuse library is simple and lite library for managing application usage limits. This library is aiming to be as simple a

utopia 23 Dec 17, 2022
An application for building micro-services in PHP ^8.

Restolia An application for building micro-services in PHP ^8. Install composer create-project restolia/restolia my-app Services Each service lives i

null 1 May 1, 2022
CleverStyle Framework is simple, scalable, fast and secure full-stack PHP framework

CleverStyle Framework is simple, scalable, fast and secure full-stack PHP framework. It is free, Open Source and is distributed under Free Public Lice

Nazar Mokrynskyi 150 Apr 12, 2022
I made my own simple php framework inspired from laravel framework.

Simple MVC About Since 2019, I started learning the php programming language and have worked on many projects using the php framework. Laravel is one

null 14 Aug 14, 2022
PHPR or PHP Array Framework is a framework highly dependent to an array structure.

this is new repository for php-framework Introduction PHPR or PHP Array Framework is a framework highly dependent to an array structure. PHPR Framewor

Agung Zon Blade 2 Feb 12, 2022