Kohana: Default controller for serving static pages

A brief overview of the problem

A framework such as Kohana is really useful when serving lots of dynamic pages, as it allows you organise both your thoughts and your code into folders, creating order from what could potentially be chaos, at the expense of having to adhere to a structured way of working, in this case setting up controllers and methods that are correctly mapped from URLs (routes).

Whilst this is necessary for dynamic pages that need access to models, helpers and such like, for static pages that literally just need to be output to the browser, it's quite a lot of overhead, and your controllers can very quickly end up bloated with itty-bitty "view this page" methods.

What would be great would be some magic method to automatically handle static pages, without having to set up an actual controller and method, that way all you really need to create is the view file, and you leave your controllers folder nice and lean.

Note: this tutorial is for Kohana 2.2. I haven't investigated how it will work with 2.3 and the routing yet. Please comment if you have something to add!

The Fallback controller

The solution is using a default or "fallback" controller that takes care of serving views from routes that don't map to an existing controller and method.

Essentially, this new controller kicks in just after the routing has drawn a blank, locates the appropriate view file, then serves it – instead of serving a 404 page.

Step-by-step

Let's a take a look at how this works in a step-by-step approach from Kohana's perspective. Don't worry – it's actually pretty simple, I've just mapped it out specifically so you can see what's happening every step of the way.

Let's start with a route

  • The user navigates to a route, lets say /about/company/history
  • Kohana looks for
    • an about controller, with
    • a company method, and intends to supply it with
    • a history argument

Here's the thing though, because we did't want the hassle of setting up ALL our controllers with methods just to load views, our about controller doesn't have a company method! So what is Kohana to do?

Let's load the Fallback Controller!
Well, normally, a 404 page would be served, but using the magic of hooks, we're going to give Kohana one last chance to do something before serving that horrid 404 page.

So:

  • The system.post_routing hook kicks in, and due to the way we've set up the hook file
  • It loads our Fallback controller, which is designed to do something useful with the route before bombing out.

Let's have the Fallback Controller do it's stuff and find the view!
In this case, we want it to attempt to find a view, so:

  • The Fallback controller builds a path from the arguments /about that will (hopefully) map to a view, in this case views/main/about.php, then
  • Attempts to find this view using Kohana::find_file, and
    • if found – loads the view!
    • if not found – serves the 404 page

Summary

Pretty useful, huh? Basically all that happened is

  • Kohana couldn't find a controller, so loaded a Fallback controller
  • The fallback controller took the route and found a view
  • Kohana loads the view (or the 404 page if the view didn't exist)

OK, perhaps it's time to look at some code

Code

You will need to create or edit code in 3 separate places:

  1. Enable hooks in your application's configuration file
  2. Create a hook file which tells Kohana what to do in the system.post_routing event
  3. Create the actual Fallback Controller that will do the finding and loading of your view files

.

application/config/config.php – Enable hooks in the main config file…

$config['enable_hooks'] = TRUE;

.

application/hooks/fallback_page.php – Add a hook file to the hooks directory…

Event::add('system.post_routing' ,'call_fallback_page');

function call_fallback_page()
{
    if (Router::$controller === NULL)
    {
        Router::$controller = 'fallback_page';
        Router::$arguments = Router::$segments;
        Router::$controller_path = APPPATH.'controllers/fallback_page.php';
    }
}

.

application/controllers/fallback_page.php – Set up a controller to do the business

class Fallback_Page_Controller extends Page_Controller // page controller is my standard page template
{

    public function __construct()
    {

    // the constructor can be omitted if you're not doing anything special,
    // as the parent constructor it is called automatically
        parent::__construct();
    }

    public function __call($function, $arguments)
    {

    // search for a view, and load it if it exists
    // it's up to you how you handle the mapping of arguments to folders here!
        $route =  implode('/', $arguments);
        if(Kohana::find_file('views/main', $route))
        {
            $this->template->content = new View('main/'.$route);
        }

    // display alternative content if not found
        else
        {
            $view = new View('common/404');
            $view->info = array($function, $arguments);
            $this->template->content = $view;
        }
    }

}

Conculsion

So now you should be able to set up a bunch of views, but needn't worry about building controllers for them if nothing exciting is happening.

The fallback controller will run, will attempt to find a matching view, and if found, will echo it the page. The main thing is – it keeps your controllers folder and classes nice and lean, and you only need to build controllers that actually DO any controlling!

Nice.

Comments are closed.