Slim Framework – using middleware for page caching in the front controller

The SlimFramework is a ‘minimal’ PHP5 framework. We’re using it in one project, integrating with Smarty, Propel and the Zend Framework (as I don’t like Zend_View, it didn’t seem worth using Zend_Controller_Action, although what we do have is very similar to one).

Anyway, when creating your front controller in Slim, you can define ‘middleware‘ (i.e. call back functions) which are executed when a route matches and runs – before your actual ‘controller’ code.

So for example, a simple route would look like :

Slim::get('/route/path/to/match', function() { echo "some output goes here"; }; );

With additional ‘middleware’ it could look like :

Slim::get('/routeh/path/to/match', $caching_middleware, $authentication_check, function() { echo "some output goes here";}; );

(Obviously in a real application you wouldn’t have echo statements in the front controller class)

The $caching_middleware could look like :

$cache_it = function () {
    $cache = Zend_Cache::factory('Page', 'File',
        array('debug_header' => true,
              'default_options' => array('cache' => true,
                                         'cache_with_get_parameters' => false,
                                         'cache_with_session_variables' => true,
                                         'cache_with_cookie_variables' => true),
        ));
    $cache->start();
};

(I’ve left the debug_header in, so it’s obvious when it’s working 🙂 ).

And $authentication_check is another call back – this time presumably checking $_SESSION for something….

1 thought on “Slim Framework – using middleware for page caching in the front controller”

Leave a Reply

Your email address will not be published. Required fields are marked *