Responses

Flight helps generate part of the response headers for you, but you hold most of the control over what you send back to the user. Sometimes you can access the Response object directly, but most of the time you'll use the Flight instance to send a response.

Sending a Basic Response

Flight uses ob_start() to buffer the output. This means you can use echo or print to send a response to the user and Flight will capture it and send it back to the user with the appropriate headers.


// This will send "Hello, World!" to the user's browser
Flight::route('/', function() {
    echo "Hello, World!";
});

// HTTP/1.1 200 OK
// Content-Type: text/html
//
// Hello, World!

As an alternative, you can call the write() method to add to the body as well.


// This will send "Hello, World!" to the user's browser
Flight::route('/', function() {
    // verbose, but gets the job sometimes when you need it
    Flight::response()->write("Hello, World!");

    // if you want to retrieve the body that you've set at this point
    // you can do so like this
    $body = Flight::response()->getBody();
});

Status Codes

You can set the status code of the response by using the status method:

Flight::route('/@id', function($id) {
    if($id == 123) {
        Flight::response()->status(200);
        echo "Hello, World!";
    } else {
        Flight::response()->status(403);
        echo "Forbidden";
    }
});

If you want to get the current status code, you can use the status method without any arguments:

Flight::response()->status(); // 200

Running a Callback on the Response Body

You can run a callback on the response body by using the addResponseBodyCallback method:

Flight::route('/users', function() {
    $db = Flight::db();
    $users = $db->fetchAll("SELECT * FROM users");
    Flight::render('users_table', ['users' => $users]);
});

// This will gzip all the responses for any route
Flight::response()->addResponseBodyCallback(function($body) {
    return gzencode($body, 9);
});

You can add multiple callbacks and they will be run in the order they were added. Because this can accept any callable, it can accept a class array [ $class, 'method' ], a closure $strReplace = function($body) { str_replace('hi', 'there', $body); };, or a function name 'minify' if you had a function to minify your html code for example.

Note: Route callbacks will not work if you are using the flight.v2.output_buffering configuration option.

Specific Route Callback

If you wanted this to only apply to a specific route, you could add the callback in the route itself:

Flight::route('/users', function() {
    $db = Flight::db();
    $users = $db->fetchAll("SELECT * FROM users");
    Flight::render('users_table', ['users' => $users]);

    // This will gzip only the response for this route
    Flight::response()->addResponseBodyCallback(function($body) {
        return gzencode($body, 9);
    });
});

Middleware Option

You can also use middleware to apply the callback to all routes via middleware:

// MinifyMiddleware.php
class MinifyMiddleware {
    public function before() {
        Flight::response()->addResponseBodyCallback(function($body) {
            // This is a 
            return $this->minify($body);
        });
    }

    protected function minify(string $body): string {
        // minify the body
        return $body;
    }
}

// index.php
Flight::group('/users', function() {
    Flight::route('', function() { /* ... */ });
    Flight::route('/@id', function($id) { /* ... */ });
}, [ new MinifyMiddleware() ]);

Setting a Response Header

You can set a header such as content type of the response by using the header method:


// This will send "Hello, World!" to the user's browser in plain text
Flight::route('/', function() {
    Flight::response()->header('Content-Type', 'text/plain');
    echo "Hello, World!";
});

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(['id' => 123]);

JSONP

For JSONP requests you, can optionally pass in the query parameter name you are using to define your callback function:

Flight::jsonp(['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.

Redirect to another URL

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 ("See Other") status code. You can optionally set a custom code:

Flight::redirect('/new/location', 401);

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

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.

Route Level Caching

If you want to cache your whole response, you can use the cache() method and pass in time to cache.


// This will cache the response for 5 minutes
Flight::route('/news', function () {
  Flight::response()->cache(time() + 300);
  echo 'This content will be cached.';
});

// Alternatively, you can use a string that you would pass
// to the strtotime() method
Flight::route('/news', function () {
  Flight::response()->cache('+5 minutes');
  echo 'This content will be cached.';
});

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.