Why Kohana is an Excellent Alternative to Zend Framework

PHP 

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 PHP framework choices. But well, it’s a bit heavyweight. Enter Kohana!


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:

  <td class="code">
    <pre class="php" style="font-family:monospace;">Kohana<span style="color: #339933;">::</span><span style="color: #004000;">modules</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
<span style="color: #666666; font-style: italic;">// 'auth'</span></pre>
  </td>
</tr>
1
2

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

  <td class="code">
    <pre class="php" style="font-family:monospace;">Kohana<span style="color: #339933;">::</span><span style="color: #004000;">modules</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
<span style="color: #666666; font-style: italic;">// 'auth'       =&gt; MODPATH.'auth',       // Basic authentication</span>
    <span style="color: #0000ff;">'cache'</span>      <span style="color: #339933;">=&gt;</span> MODPATH<span style="color: #339933;">.</span><span style="color: #0000ff;">'cache'</span><span style="color: #339933;">,</span>      <span style="color: #666666; font-style: italic;">// Caching with multiple backends</span>
<span style="color: #666666; font-style: italic;">// 'codebench'  =&gt; MODPATH.'codebench',  // Benchmarking tool</span>
    <span style="color: #0000ff;">'database'</span>   <span style="color: #339933;">=&gt;</span> MODPATH<span style="color: #339933;">.</span><span style="color: #0000ff;">'database'</span><span style="color: #339933;">,</span>   <span style="color: #666666; font-style: italic;">// Database access</span>
<span style="color: #666666; font-style: italic;">// 'image'      =&gt; MODPATH.'image',      // Image manipulation</span>
<span style="color: #666666; font-style: italic;">// 'orm'        =&gt; MODPATH.'orm',        // Object Relationship Mapping</span>
<span style="color: #666666; font-style: italic;">// 'unittest'   =&gt; MODPATH.'unittest',   // Unit testing</span>
<span style="color: #666666; font-style: italic;">// 'userguide'  =&gt; MODPATH.'userguide',  // User guide and API documentation</span>

));

1
2
3
4
5
6
7
8
9
10

The Database Schema

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

  <td class="code">
    <pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">DROP</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`sessions`</span>;

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;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

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:

  <td class="code">
    <pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>

  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, ), );

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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:

  <td class="code">
    <pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'SYSPATH'</span><span style="color: #009900;">&#41;</span> or <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'No direct script access.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>

  return array ( // Override the default configuration ‘apc’ => array ( ‘driver’ => ‘apc’, ‘default_expire’ => 3600, ), );

1
2
3
4
5
6
7
8
9
10
11

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:

  <td class="code">
    <pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'SYSPATH'</span><span style="color: #009900;">&#41;</span> OR <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'No Direct Script Access'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>

  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; } }

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

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:

  <td class="code">
    <pre class="html" style="font-family:monospace;">&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;A Simple Kohana Application&lt;/title&gt;
    &lt;style type="text/css"&gt;
        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>

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

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.


You might also be interested in these tutorials too...

Fri, Apr 27, 2012

Zend Form Mastery with Zend Config - Part 1 Custom Filter Paths

When you’re working with Zend Form you keep your configuration as much out of code as you can - right? Well, if you’ve been working withZend Form for more than a little while, you know that Zend Config really makes that pretty simple - well, some of the time. In this series we look, comprehensively at how to do it all with Zend_Config.

Tue, Oct 5, 2010

Do you i18n?

What’s your attitude to i18n? Are you not quite sure what i18n is? Well, according to Wikipedia, it’s:

Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting internationalized software for a specific region or language by adding locale-specific components and translating text.

Wed, Jan 30, 2013

Zend ServiceManager - Web Application Development Simplified

The Zend ServiceManager simplifies the web application development process by making configuration a breeze. In this, the 4th post introducing Zend Framework 2, you will learn what the ServiceManager is how to use it and how it simplifies applicaiton development time.


Want more tutorials like this?

If so, enter your email address in the field below and click subscribe.

You can unsubscribe at any time by clicking the link in the footer of the emails you'll receive. Here's my privacy policy, if you'd like to know more. I use Mailchimp to send emails. You can learn more about their privacy practices here.

Join the discussion

comments powered by Disqus