Tutorial: Using Kohana as a library

If you're working with an existing codebase it's often difficult to modernise the code as it would mean an complete rewrite and there's rarely the time. An alternative is to improve the codebase incrementally as best you can, gradually outsourcing code to external libraries to reduce the amount of old code there is to maintain.

This post is a tutorial on how to include the Kohana PHP framework into existing PHP applications, without having to use the routing and HMVC request handling features.

Disclaimer: This tutorial is written for Kohana version 3.1.2, if you are using a different version we recommend you double check the Kohana source files we draw on to in this tutorial as they may differ in other versions.

In normal usage of the Kohana framework, the index.php file acts as the request handler; it sets up the environment (lines 3-74), loads the system configuration (line 102) and then handles the request (lines 108-111).

This tutorial walks you through the steps required to create a file we'll call include.php which will allow you to include Kohana from your exiting PHP applications.

Demo application

The following file will serve as our (insultingly simple) demo application for this tutorial.

Install Kohana

Download and install the Kohana framework onto your system, exactly how you do this, or where you is put it, isn't important. From this point on, we'll be referring to the location of the Kohana libraries as the kohana directory.

Create a common setup file

Since index.php and include.php will duplicate a lot of code, we're going to move that code to a third file, common.php. The bulk of the code is unchanged; we've changed the install check to exit after rather than return after rendering (lines 82-83), and removed the request execution.

The new file returns the request object (line 109), rather than fully executing the request, so that, if you do define routes, the Request::$initial variable will be set up correctly.

As the file is quite large, view it in full on github.

Alter Kohana's index.php

Having moved most of the code from Kohana's index.php to common.php the new Kohana index.php contains only this:

Create include.php

Our include.php file is also pretty simple. The try-catch clause is needed because if the request matches no routes Kohana will throw an HTTP_Exception_404 exception.

NB: Due to the way Kohana currently works, if the request matches no routes it will fail to instantiate an object, and Request::$current and Request::$initial will not be available.

Integrated application

Now that we're set up, we can add Kohana into our application using a single include, and then we're good to go.