Why Kohana is an Excellent Alternative to Zend Framework

kohana php logo

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.

PHP
  • dzschille

    Thanks for the article. I guess line 19 in Controller_Users should be 
    if (empty($usersList)) {

    • http://www.matthewsetter.com/ maltblue

       @dzschille thanks for commenting and your feedback about the error in the code. I’ve changed that as required. Much appreciated.

  • http://www.synet.sk lubosdz

    Yes, there are better alternatives than ZF, no question about it.
     
    Kohana is nice but not the best choice around because:
    - database ORM is a bottleneck, supports only 2-3 RDBMS,
    - does not support Web2 elements, widgets
     
    Otherwise its not really bad, definitely better than ZF.
     
    Very similar to Kohana is Yii, however it offers significantly more robust functionalities – ORM based on PDO supports 5 RDBMS, web2 widgets based on Juery UI, built-in support for integration with 3rd party libraries.
     
    Of course, judgements like these are always more or less subjective:-))
     
    ZF will be alive as long as it is considered industrial standard by big companies (where decisions are made by non-PHP guys) that are afraid small frameworks will die unlike ZF.
     
    Lubos

    • http://www.matthewsetter.com/ maltblue

       @lubosdz thanks for your feedback. I admit that I do write this as a non-power kohana user. And I believe that you’re right about the points that you’ve made.
       
      However, from what I’ve seen, one of the best things about Kohana is that it doesn’t force you down a specific path and allows you to link in to a load of 3rd party libraries to quickly extend it. So you can always write what it doesn’t have in a way that you believe is the best way to go.
       
      Whilst I’m a big fan still of zend it’d be great to see it have more robust command-line or GUI tooling, such as Yii, which is exceptional IMHO. It’d really help get big projects, where it shines, up and running quickly and reliably.
       

    • zenlord

       @lubosdz ‘not supporting Web2 elements, widgets’ is one of the best features of Kohana: it doesn’t try to do everything and the kitchensink – it sticks to what a PHP framework should do and lets you load assets like JS-frameworks and views

  • rommelxcastro

    good article, i’m learning ZF now, i have a few years working with CI, is good to read the perspective about others frameworks from a ZF fan

    • http://www.matthewsetter.com/ maltblue

       @rommelxcastro I’ve not worked much with CI myself, well some years ago yes. But what would you say are the key differences between CI and Zend? How are you finding Zend so far?

      • rommelxcastro

         @maltblue zend is amazing, for now i’m just learning but i’m waiting for the perfect project and use it, well CI is really easy
        CI can be for a junior developer who wants to learn about objects, mvc, oop and zend for more experienced programmers

        • hussainweb

           @rommelxcastro  @maltblue I am not sure if I agree with that. In my opinion, if you have to use CI to learn, it would be better to extend it with techniques for HMVC, view components, ORM, class-based helpers (not the way commonly used in CI), etc… This helps developing a mindset of avoiding functions as much as possible and sticking to objects, which, as used in Kohana, is really efficient.

        • http://www.matthewsetter.com/ maltblue

           @hussainweb  @rommelxcastro This is turning in to an interesting discussion. I don’t have enough experience to either defend or criticise CI. But I’m sure that it’s a bit more than for junior developers. This framework discussion seems to have lit a spark. Might be worth a post comparing a series of the current frameworks. Are you both keen for that? 

  • hussainweb

    I have only worked with Zend for a little time, just configuration and little maintenance. I have used Kohana for a few non-trivial applications and it is absolutely a pleasure to write code with it. I had also used CI for a project earlier but once I started using Kohana, I almost always use it where applicable.
     
    So far, Kohana has solved all the requirements I have faced with it in a very elegant manner. I have never noticed issues with the ORM (I almost always use MySQL) and as far as widgets are concerned, I have written a little abstraction over views to make it easier to handle such scenarios. I have heard a lot about Yii and I might consider it for another project, given time.

    • http://www.matthewsetter.com/ maltblue

       @hussainweb thanks for your feedback. So you’re converted to Kohana then? I think I’m partly heading the same way, but will still be using Zend for a while to come. Do you have a Github repository, or similar with your Kohana code samples available at all? I’d love to see some as I’m still learning about Kohana myself. 

      • hussainweb

         @maltblue I keep thinking about it but I don’t have an (active) Github account yet. I will start on that soon.

        • http://www.matthewsetter.com/ maltblue

           @hussainweb Great to hear. Looking forward to seeing it.

  • FrantisekMasa

    I work in Kohana 3.2 about 6 months now and I just love it. HMVC architecture (subrequests, etc..) makes a lot of stuff easier and faster.
     
    One of the best things on Kohana is IMHO that, it’s very easy to understand, so you’re able to write your first own modules in a few days.

    • http://www.matthewsetter.com/ maltblue

      @FrantisekMasa I couldn’t agree more. It’s really easy to understand with loads of options ready to be set, right out of the box. All that power yet so simple to command.

  • RomanDraconyTsjupa

    In comparison to Yii Kohana is indeed the most straightforward thing in the world. And it’s not slower too, the benchmarks on Yii site are completely biased. You can take a look at some more relevant benchmarks here: 
    http://phpixie.com/blog/php-framework-benchmark/