Kohana: The Swift PHP Framework

Kohana is a PHP 5 framework that uses the Model View Controller (MVC) architectural pattern. There are several reasons why you should choose Kohana but the main ones are security, weightlessness and simplicity. In this tutorial, I'll introduce its main features, and, with a simple demonstration, I'll show you how much time Kohana can potentially save you.

Step 1: What is Kohana?

Kohana is a PHP5 framework that uses the Model View Controller architectural pattern. MVC keeps application logic
separate from the presentation. This allows us to create cleaner code and save time for bug searching.
In unfamiliar with this pattern:

A Model represents data on which the application operates. Usually a database.

A View contains presentation code such as HTML, CSS and JavaScript.

A Controller interprets input from the user and sends to the model and/or view.

Kohana was originally a fork of CodeIgniter (CI), which is an open-source product from EllisLab. There are many similarities between CI and Kohana, but all of the code is either new or completely rewritten. As you can read on the official Kohana web site, the main features are:

Highly secure

Extremely lightweight

Short learning curve

Uses the MVC pattern

100% UTF-8 compatible

Loosely coupled architecture

Extremely easy to extend

Step 2: Downloading Kohana

Let's get started. Visit Kohana's official web site http://kohanaphp.com and click on the green box in the right corner to download the latest version. All Kohana libraries, helpers, and views are included in the default download package, but you may select extra modules, vendor tools, and languages if you want. For the purpose of this tutorial, the default package can be enough. Click on "Download Kohana!" to begin the download.

Step 3: Installing Kohana

Once you've finished downloading it:

Unzip

Rename the "Kohana_vx.x.x" folder to "kohana" and upload it to your web server document root

If you are using a unix-like system, the installation's subdirs may have lost their permissions during zip extraction. Chmod them all to 755 by running find . -type d -exec chmod 755 {} \; from the root of your Kohana installation.

Make sure the application/logs and application/cache directories are writeable. Chmod to 666.

Now, point your browser to http://localhost/kohana/. Automatically, the framework will call the install.php script and check for your server requirements.

Kohana will run in nearly any environment with minimal configuration. There are a few minimum server requirements:

Server with Unicode support

PHP version >= 5.2.3

An HTTP server. I suggest you use XAMPP. XAMPP is an easy all-in-one tool to install MySQL, PHP and Perl.

Database (MsSQL, MySQL, MySQLi, PostgreSQL, PDOSqlite)

There are also some required extensions.

PCRE

iconv

mcrypt

SPL

If your installation completes successfully, you will be redirected to this test page:

If any of the tests fail, you must correct them before moving forward.

If all tests have passed, go to the Kohana directory and remove or rename the install.php script. Refresh, and you will see a welcome page like this:

Step 4: Configuring Kohana

Kohana is ready to go. No other configuration is needed. This framework is amazing. Isn't it? Let's review some code. Follow me.

Step 5: Your first Kohana Project

Canonical programming tutorials start with the "Hello world" example. I think, instead, that a simple application can give you a clear idea how the framework works. So, we will build a CD collection manager -- just for a fun demonstration. Before we start coding, a brief introduction to Kohana file system is required.

Our application will be placed in the application folder. In this folder there are several sub folders but we need the following for our project:

views folder hosts our custom files written in HTML (or any markup language or script needed to display data and interface controls to the user)

The remaining sub folders are not required for this tutorial, so I invite you to learn more on the Kohana web site.

The system folder host the Kohana core and the Kohana tools like libraries, helpers and predefined configuration files. In this project we will use some libraries and some helpers - good tools to speed up your work.

The assets folder is not a predefined Kohana folder. I have created it for media files like CSS, JS, and images. I'll show you how to include these files in the project.

The modules folder is the place to put reusable collections of related files that together add a particular functionality to an application. The authentication module, provided by the Kohana team, is an example of module.

This is a very brief introduction to the Kohana file system, but it's enough for the purposes of this tutorial. I don't want to bore you more with theory.

Step 6: Project Database

I have chosen MySQL as my DBMS, but remember that Kohana also supports MsSQL, MySQLi, PostgreSQL, PDOSqlite. Create a database called "cd_collection" or choose the name you prefer, and run the following SQL through phpMyAdmin or any tool to handle the administration of MySQL.

This code tells Kohana to connect to a MySQL database called "cd_collection" on localhost with the username "root" and the password "root". You have to change these settings according to your database server configuration.

Step 7: Create the Controller

Let's now create our first controller. Remember these conventions.

controller filename must be lowercase, e.g. album.php

controller class must map to filename and capitalized, and must be appended with _Controller, e.g. Album_Controller

must have the Controller class as (grand)parent

Also, remember how Kohana structures its URLs and how you can call a controller method; e.g http://hostname/kohana_directory/index.php/controller/function.

PHP5 OOP is a prerequisite. So if you aren't well-versed, you can learn more here.

The constructor function, called __construct, initializes the class and calls the parent constructor.
The index function is the default function, so it will be called if we call the controller without
specifying any function (e.g. http://localhost/index.php/kohana/album. After the name controller
there isn't any function, the default index function will be called.)

Given these basic rules, let's focus on our application. The album controller implements all the actions for
the albums collection management. This controller allows us to create a new album, to show the albums stored in our database,
to update an album, and to delete an album.

So, let's change the class as follows.

Create a file called album.php in application/controllers/ and paste the following.

In this method you can see how the model and view object are used to access relative methods. "get_list" is a model method (we will see it later) that returns all the albums stored in the database. The result is saved in the "$album_list" array. To pass the result array from the controller to the view, the "set" method is called on the view object. This method requires two parameters: a new empty variable (album_list) to contain data of an existing variable ($album_list). Now the new variable "album_list" contains the $album_list array (we will see later how to show the content in the view). The method "render", with the TRUE parameter, is necessary to output data to the browser.

The show_create_editor method shows the user interface to insert a new album.

$album_data is an array that contains the POST data from the view. To save the album, the array is passed to the create model method. The last line is a call to a helper method. Helpers are simply functions that assist you with development. The helper classes are automatically loaded by the framework. Helpers are declared as static methods of a class, so there is no need to instantiate the class. In this case the method "redirect" of the helper "url" is called and tells Kohana to redirect the browser to the album controller. This avoids a new insert (for example pressing F5).

"Helpers are simply functions that assist you with development."

The update and delete methods work in the same manner as the create method above.

The last method get_genres_list gets the genres list from the model ($db_genres_list) and builds a new array ($genres_list) for the select box in the views.

This model is very simple so I'll waste no further time to comment upon it. The Models and the controller are ready to go. Let's now work on the Views.

Step 9: Create the Project View

Views are files that contain the presentation layer for your application. The purpose is to keep this information separate from your application logic for easy reusability and cleaner code. For this project, three views are required: a view to list the album collection, a view to create a new album, and a view to edit an existing album.

Create a file called list.php in application/views/ and paste the following code in:

This view shows an html page containing a list of all albums. This list has been created using foreach loop that prints the information in an html table. For each album row, there are two images: a "red cross" and a "pocketbook". They link respectively the controller delete method and the update method. Both pass the album id to the album controller using a get request. Above the list there is a button to create new albums. In this code we also make use of an html helper provided by Kohana that speeds up operations to write html pages.

The first one is a simple editor that enables the user to insert information about a new album.
The fields like author and name will be inserted using an html input and genre using a
combo box. Once the user clicks on the create button, all information is passed,
as a POST request, to the create/update method in the album controller. When the controller receives these posted
variables, it calls the model that inserts a new album into the database. The forms, in both views, makes use of Kohana form helper.

To give a bit of style to our application, create the assets folder in the Kohana root at the same level of the application folder. Now, open it and create two new folders: css and images.

That's all. Point your browser to http://localhost/kohana/index.php/album and you should see something similar to this:

If you try to create a new album or to edit an existing one you should see something similar to this:

Step 10: Final Thoughts

Of course, some improvements are required for this application but with a small amount of code, you've created a little web application.
Now, you know how to use the MVC pattern with Kohana, and how to use database libraries and helpers. To learn more, read the official documentation.

Thanks to Kohana, code maintenance is an easy task, and adding new features is a cinch. I hope you enjoyed this tutorial. Stay tuned to learn more about Kohana.

Hello, my name is Cristian Gilè, I'm a freelance PHP/MySQL developer and I work in the beautiful city of Brescia, Italy. As a Web developer, I'm specialise in building custom PHP/MySQL web applications and Kohana and Codeigniter frameworks are my main tools. My skillset also includes xHTML, CSS, JQuery. My development environment of choice is Ubuntu using Aptana Studio as editor/debugger. What else to say...follow nettuts for more tutorials by me.