Why Kohana is an Excellent Alternative to Zend Framework

As you know from reading Malt Blue, I’m rather a Zend Framework fan. Whether it’s the controller plugins, easily adding RSS feeds to applications, configuration with Zend Config or more – I really believe it’s one of the best framework choices that PHP has to offer.

However recently I’ve been doing a lot of research in to some of the best PHP frameworks and codebases, including Symfony 1 & Symfony 2, Drupal, CakePHP and Kohana for a technical documentation project that I’ve been working on.

As a part of that project, I’ve had to really come up to speed about how they’re composed and the process for doing core configuration, including:

  • Specifying where the session information is stored
  • Specifying where the log information is stored
  • Automagically determining the current, running, environment

Well, to say the least, I was really surprised at just how simple, lightweight and easy Kohana is to use. Wow, what a true breath of fresh air it is after using Zend Framework for so long now.

Update: This page has been translated into Spanish by Maria Ramos from Webhostinghub.com.

How so?

  • It didn’t force me to follow a rigid set of configuration and layout practices
  • It provides a wealth of built in options and resources in a well commented configuration file: application/bootstrap.php
    • All you need to do is uncomment the option you want and it’s available to the application
  • It makes it dead simple to override core classes. There’s no need to explicitly add file paths.
  • It’s very fast
  • It’s easy to add in 3rd party libraries to extend core functionality
  • It’s easy to create modules to add in functionality that’s not already there

Now don’t get me wrong, I’m not leaving Zend Framework behind, I’m still a big fan. But I have to be honest and acknowledge that Zend Framework can be a lot of work to get started with and to setup testing with as well.

Personally, I believe it’s worth the effort for the beautiful product that you get with it – but well, do you need to go through the amount of effort every time? No!

If you’re looking for a feature rich, flexible, fast and sensibly configurable PHP framework, right out of the box to get up to speed with, that your developers can learn quickly, yet learn some very good practices, then look no further than Kohana.

What’s more, it’s got some really gifted PHP developers backing it.

A Simple Application

Now it’s one thing for me to make these claims, but as developers, we need to see assertions backed up and we love to see code. So in the following application, we’re going to create a simple application that has database and cache support and in a controller, uses that support to displays a list of users from a database, using a cache to speed up the process, where possible.

So before we go any further, grab a copy of the latest, stable, version of Kohana, version 3.2.0 at the time of writing. Extract that to your local development environment and get it ready to go with your webserver of choice.

The Core Configuration

In your extracted codebase, open up application/bootstrap.php. In it, search for the following line:

1
2
Kohana::modules(array(
    // 'auth'

You’ll see that all the options in the array are commented out. Change it to match the configuration below.

1
2
3
4
5
6
7
8
9
10
Kohana::modules(array(
    // 'auth'       => MODPATH.'auth',       // Basic authentication
        'cache'      => MODPATH.'cache',      // Caching with multiple backends
    // 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
        'database'   => MODPATH.'database',   // Database access
    // 'image'      => MODPATH.'image',      // Image manipulation
    // 'orm'        => MODPATH.'orm',        // Object Relationship Mapping
    // 'unittest'   => MODPATH.'unittest',   // Unit testing
    // 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
));

The Database Schema

I’m using MySQL for this application. So if you’re using another database, please change the schema as appropriate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DROP TABLE IF EXISTS `sessions`;
CREATE TABLE `sessions` (
    `session_id` VARCHAR(24) NOT NULL,
    `last_active` INT(10) UNSIGNED NOT NULL,
    `contents` text NOT NULL,
    PRIMARY KEY (`session_id`),
    KEY `last_active` (`last_active`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
DROP TABLE IF EXISTS `tblUsers`;
CREATE TABLE `tblUsers` (
    `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `firstName` VARCHAR(100) NOT NULL,
    `lastName` VARCHAR(100) NOT NULL,
    `emailAddress` VARCHAR(200) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
 
LOCK TABLES `tblUsers` WRITE;
INSERT INTO `tblUsers` VALUES (1,'matthew','setter','ms@example.com'),(2,'don','bradman','db@example.com'),(3,'alan','border','ab@example.com');
UNLOCK TABLES;

This schema gives us two tables; one will hold the session information and the second will be hold a set of users that we’ll query and display shortly. Load that in using your MySQL client of choice and then let’s look at the controller setup.

The Database Configuration

In application/config/database.php, add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
return array
(
    'default' => array
    (
        'type'       => 'mysql',
        'connection' => array(
            'hostname'   => 'localhost',
            'username'   => 'cc_dev',
            'password'   => 'cc_dev',
            'persistent' => FALSE,
            'database'   => 'cloudcontrol_kohana',
        ),
        'table_prefix' => '',
        'charset'      => 'utf8',
        'profiling'    => TRUE,
    ),
);

This provides a default database configuration for use. Change it to use the settings in your local development environment.

The Cache Configuration

In application/config/cache.php, add the following code:

1
2
3
4
5
6
7
8
9
10
11
<?php defined('SYSPATH') or die('No direct script access.');
 
return array
(
    // Override the default configuration
    'apc'   => array
    (
        'driver'             => 'apc',
        'default_expire'     => 3600,
    ),
);

This says that we’re using APC for our application cache.

The Controller

Under application/classes/controller/ create a new file called users.php. In that file, put the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php defined('SYSPATH') OR die('No Direct Script Access');
 
Class Controller_Users extends Controller_Template
{
    public $template = 'users';
 
    public function action_index()
    {
        $db = Database::instance(Kohana::$environment);
 
        // Change the default cache driver to apc
        Cache::$default = 'apc';
 
        // Create a new instance of cache using the default group
        $cache = Cache::instance();
 
        $usersList = Cache::instance()->get('usersList', FALSE);
 
        if (empty($usersList)) {
             $results = DB::select('id', 'emailAddress')->from('tblUsers')->execute($db);
             $usersList = $results->as_array();
             Cache::instance()->set('usersList', $results->as_array());
        }
 
        $this->template->users = $usersList;
    }
}

What that code does is to say that we’ll be using a template called users.php. After that, we retrieve the database configuration based on the automatically determined environment configuration and we set the cache to use the APC cache.

Then we retrieve a list of id’s and email addresses from the table, tblUsers, if it’s not able to be loaded from the APC cache. After that, we assign the users list to the template variable users and we’re ready to look at our view variable.

The View

Under application/views, create a file called users.php and in it put the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<html>
    <head>
        <title>A Simple Kohana Application</title>
        <style type="text/css">
            body {font-family: Georgia;}
            h1 {font-style: italic;}
 
        </style>
    </head>
    <body>
        <h1>A Simple Kohana Application</h1>
        <table cellspacing="2" cellpadding="4" border="2" width="100%">
            <tr>
                <th>User ID</th>
                <th>User Email</th>
            </tr>
        <?php foreach($users as $user) : ?>
            <tr>
                <td><?php print $user['id']; ?></td>
                <td><?php print $user['emailAddress']; ?></td>
            </tr>            
        <?php endforeach; ?>
        </table>
    </body>
</html>

What this does is to iterate over the value of the users template variable that we assigned earlier, displaying the user id and email address in a simple HTML table. Nothing could be easier.

The Finished Application

Now that all that’s done, open up your application to the url: http://your_configured_url/users. All being well, what you’re going to see a page a lot like the following:

A simple Kohana PHP application - easier than Zend Framework

You can see that with so little effort, we have a header and a table outputting the user records from the table we setup earlier. What could be easier? Not much really.

Now, to be fair, this is a pretty trivial example and I’m sure experts in both the Zend Framework and Kohana camps could write a much better application. But really, this is so simple, so fast and so easy to build. What’s more it’s easy to follow and configure for junior and intermediate skilled developers alike.

Do you use Zend Framework? Do you think that Kohana’s a simpler choice? Share your thoughts in the comments.


Share This


About Matthew

Matthew Setter Matthew Setter is a software developer specializing in PHP, Zend Framework, and JavaScript. He's also the host of FreeTheGeek.fm, the podcast about the business of freelancing as a software developer and technical writer, and editor of Master Zend Framework, dedicated to helping you become a Zend Framework master?.

Find Matthew on LinkedIn Find Matthew on Twitter Find Matthew on Facebook Find Matthew on Google+

Like That?

Don’t miss the next post. Drop your email in the box below, and get it straight to your inbox, PLUS exclusive content only available by email. No spam, and you can unsubscribe at any time.