Kohana: The Swift PHP Framework

Kohana: The Swift PHP Framework

Jul 9th in PHP by Cristian Gilè

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.

PG

Author: Cristian Gilè

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.

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:

  1. Unzip
  2. Rename the "Kohana_vx.x.x" folder to "kohana" and upload it to your web server document root
  3. Edit the global configuration file application/config/config.php as follows
  4. $config['site_domain'] = 'localhost/kohana';
  5. 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.
  6. Make sure the application/logs and application/cache directories are writeable. Chmod to 666.
  7. 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:

  • config folder hosts all the configuration files coded as simple static arrays.
  • controllers folder hosts our custom controllers class
  • models folder hosts our custom models class
  • 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.

CREATE TABLE `albums` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(50) collate utf8_bin NOT NULL,
  `author` varchar(50) collate utf8_bin NOT NULL,
  `genre_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `genre_id` (`genre_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=19 ;

INSERT INTO `albums` (`id`, `name`, `author`, `genre_id`) VALUES
(2, 'Lines, Vines And Trying Times', 'Jonas Brothers', 16),
(3, 'The E.N.D.', 'The Black Eyed Peas', 16),
(4, 'Relapse', 'Eminem', 18),
(5, 'Monuments And Melodies', 'Incubus', 1),
(6, 'Thriller', 'Michael Jackson', 16),
(7, 'Back in Black', 'AC/DC', 4),
(8, 'The Dark Side of the Moon', 'Pink Floyd', 4),
(9, 'Bat out of Hell', 'Meat Loaf', 4),
(10, 'Backstreet Boys', 'Millennium', 16),
(11, 'Rumours', 'Fleetwood Mac', 4),
(12, 'Come on Over', 'Shania Twain', 16),
(13, 'Led Zeppelin IV', 'Led Zeppelin', 4),
(14, 'Jagged Little Pill', 'Alanis Morissette', 4),
(15, 'Sgt. Pepper''s Lonely Hearts Club Band', 'The Beatles', 16),
(16, 'Falling into You', 'Céline Dion', 16),
(17, 'Music Box', 'Mariah Carey', 16),
(18, 'Born in the U.S.A.', 'Bruce Springsteen', 4);

CREATE TABLE `genres` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(50) collate utf8_bin NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=22 ;

INSERT INTO `genres` (`id`, `name`) VALUES
(1, 'Alternative Rock'),
(2, 'Blues'),
(3, 'Classical'),
(4, 'Rock'),
(5, 'Country'),
(6, 'Dance'),
(7, 'Folk'),
(8, 'Metal'),
(9, 'Hawaiian'),
(10, 'Imports'),
(11, 'Indie Music'),
(12, 'Jazz'),
(13, 'Latin'),
(14, 'New Age'),
(15, 'Opera'),
(16, 'Pop'),
(17, 'Soul'),
(18, 'Rap'),
(20, 'Soundtracks'),
(21, 'World Music');

ALTER TABLE `albums`
  ADD CONSTRAINT `genre_inter_relational_constraint` FOREIGN KEY (`genre_id`) REFERENCES `genres` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

As you can see, the SQL creates two tables, albums and genres, and populates them with some data. The last SQL statement adds a constraint for the foreign key "genre_id".

The database structure is very simple and doesn't need much explanation.

Now, you have to tell Kohana where your database is located and how to access it. Edit the global configuration file system/config/database.php as follows

$config['default'] = array
(
	'benchmark'     => TRUE,
	'persistent'    => FALSE,
	'connection'    => array
	(
		'type'     => 'mysql',	
		'user'     => 'root',	
		'pass'     => 'root',	
		'host'     => 'localhost',	
		'port'     => FALSE,		
		'socket'   => FALSE,		
		'database' => 'cd_collection'
	),
	'character_set' => 'utf8',
	'table_prefix'  => '',
	'object'        => TRUE,
	'cache'         => FALSE,
	'escape'        => TRUE
);

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.

Let's take a look at this simple controller.

<?php defined('SYSPATH') OR die('No direct access allowed.');

class Album_Controller extends Controller
{ 
	public function __construct()	
 	{ 
		parent::__construct();
	}
 	
	public function index()
 	{
 	  	echo "My first controller";	
	}
}

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.

<?php defined('SYSPATH') OR die('No direct access allowed.');
	
class Album_Controller extends Controller
{
	 private $album_model; 
	 private $genre_model;
	 
	 private $list_view;
	 private $create_view;
	 private $update_view;
 
	public function __construct()	
 	{ 
		parent::__construct();
		$this->album_model   = new Album_Model;
		$this->genre_model  	= new Genre_Model;
	  	$this->list_view   	= new View('list');
	  	$this->update_view  	= new View('update');
	  	$this->create_view  	= new View('create');
	}
 
 	public function index()
 	{
  		$this->show_albums_list();
 	}
		
	private function show_albums_list()
	{
		$albums_list = $this->album_model->get_list(); 
		$this->list_view->set('albums_list',$albums_list);
		$this->list_view->render(TRUE); 
	}
	
 	public function show_create_editor()
 	{
 		$this->create_view->set('genres_list',$this->get_genres_list());
  		$this->create_view->render(TRUE);
 	}
 
 	public function show_update_editor($id)
 	{
		$album_data = $this->album_model->read($id);
		$this->update_view->set('album_id',$album_data[0]->id);
		$this->update_view->set('name',$album_data[0]->name);
		$this->update_view->set('author',$album_data[0]->author);
		$this->update_view->set('genre_id',$album_data[0]->genre_id);
		$this->update_view->set('genres_list',$this->get_genres_list());
		$this->update_view->render(TRUE);
 	}
 
 	public function create()
 	{ 
		$album_data=array(
		'name'    	=> $this->input->post('name'),
		'author'  	=> $this->input->post('author'),
		'genre_id'  => $this->input->post('genre_id')
		);
		$this->album_model->create($album_data);
		url::redirect('album');
 	}
 
	public function update()
	{ 
		$album_data = array(
			'name'    	=> $this->input->post('name'),
			'author'  	=> $this->input->post('author'),
			'genre_id'  => $this->input->post('genre_id')
		);
		$this->album_model->update($this->input->post('album_id'),$album_data);
  		url::redirect('album');
 	}
  
  	public function delete($id)
 	{
		$this->album_model->delete($id);
		url::redirect('album');
 	}
 
	private function get_genres_list()
	{
		$db_genres_list  = $this->genre_model->get_list(); 
		$genres_list  = array();
		
		if(sizeof($db_genres_list) >= 1)
		{
			foreach($db_genres_list as $item)
			{
				$genres_list[$item->id] = $item->name;
			}
		}
		return $genres_list;
 	}
}

Let me explain what this code does.

Five members variables are declared at the top of the class:

private $album_model; 
private $genre_model;
		 
private $list_view;
private $create_view;
 private $update_view;

These members are private because I want to limit visibility only to this class.

In the construct method the model and view objects are created using the five members:

$this->album_model   = new Album_Model;
$this->genre_model  	= new Genre_Model;
$this->list_view   	= new View('list');
$this->update_view  	= new View('update');
$this->create_view  	= new View('create');

To create a model object use this syntax:

$obj_name = new Name_Model;

To create a view object, use this syntax:

$obj_name = new View('view_filename_without_extension');

Now there are two objects to access the album and genre model, and three objects to access the views needed to render the presentation.

The index method call the show_albums_list method that lists all albums stored in the database.

$albums_list = $this->album_model->get_list(); 
$this->list_view->set('albums_list',$albums_list);
$this->list_view->render(TRUE); 

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.

$this->create_view->set('genres_list',$this->get_genres_list());
$this->create_view->render(TRUE);

The list of the genres is passed to the view.

The show_update_editor method shows the user interface to update an existing album.

$album_data = $this->album_model->read($id);
$this->update_view->set('album_id',$album_data[0]->id);
$this->update_view->set('name',$album_data[0]->name);
$this->update_view->set('author',$album_data[0]->author);
$this->update_view->set('genre_id',$album_data[0]->genre_id);
$this->update_view->set('genres_list',$this->get_genres_list());
$this->update_view->render(TRUE);

"read" is a model method (we will see it later) that returns data ($album_data) of the album with an id equal to $id. Then, every single element of the returned data album is passed to the view.

The create method receives data, for a new album, from the view and data are stored in the database.

		$album_data=array(
		'name'    	=> $this->input->post('name'),
		'author'  	=> $this->input->post('author'),
		'genre_id'  => $this->input->post('genre_id')
		);
		$this->album_model->create($album_data);
		url::redirect('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.

		$db_genres_list  = $this->genre_model->get_list(); 
		$genres_list  = array();
		
		if(sizeof($db_genres_list) >= 1)
		{
			foreach($db_genres_list as $item)
			{
				$genres_list[$item->id] = $item->name;
			}
		}
		return $genres_list;

Step 8: Create Project Model

Let's now create models for our web application. Remember these conventions.

  • model filename must be lowercase, e.g. album.php
  • model class must map to filename and be capitalized, and must be appended with _Model, e.g. Album_Model
  • must have the Model class as (grand)parent

Here is the album model code. Create a file called album.php in application/models/ and paste the code below on it.

<?php defined('SYSPATH') OR die('No direct access allowed.');

class Album_Model extends Model
{
 	private $album_table;
 	private $genre_table; 
 
  	public function __construct()
    	{
      		parent::__construct();
  		$this->album_table = 'albums';
		$this->genre_table = 'genres';
  	}
  
  	public function read($id)
  	{
		$this->db->where('id', $id);
		$query = $this->db->get($this->album_table); 
  		return $query->result_array();
 	}
  	
	public function delete($id)
  	{
		$this->db->delete($this->album_table, array('id' => $id));
  	}
  
  	public function update($id,$data)
  	{
		$this->db->update($this->album_table, $data, array('id' => $id));
  	}
  	
	public function create($data)
  	{
   		$this->db->insert($this->album_table, $data);
  	}
 	
	public function get_list()
 	{
  		$this->db->select('albums.id as id,albums.name as name,albums.author as author, genres.name as genre');  
  		$this->db->from($this->album_table);  
  		$this->db->join($this->genre_table,'genres.id','albums.genre_id');
  		$query = $this->db->get();
  		return $query->result_array();
	}
}

All the methods in the models make use of the Query builder syntax. This Kohana tool speeds up database development times and simplify the queries creation.

Two members variables are declared at the top of the class:

			private $album_table;
			private $genre_table; 
	

These members are private because I want to limit the visibility only to this class. They are the containers for the database tables names.

The first line in the constructor method loads the Kohana database library into $this->db. In the second and third lines the two class members are initialized.

parent::__construct();
$this->album_table = 'albums';
$this->genre_table = 'genres';

The query in the read method retrieves album records that have a certain identifier ("$id").

			$this->db->where('id', $id);
		 	$query = $this->db->get($this->album_table); 
	  	 	return $query->result_array();
	

The query in the delete method deletes the albums table row that have a certain identifier ("$id").

$this->db->delete($this->album_table, array('id' => $id));
	

The query in the update method updates the albums table row that has a certain identifier ("$id") with new values from the "$data" array.

$this->db->update($this->album_table, $data, array('id' => $id));
	

The "$data" array must contain record names as keys of the array, and value as values of the array. The "$data" array must have this form:

$data = array(
	'name' 			=> 	'album_name',
	'author'		=>	'author_name',
	'genre_id'		=>	'genre_id'	
	);
	

The query in the create method inserts a new record with values of the "$data" array.

$this->db->insert($this->album_table, $data);
	

The "$data" array must have this form:

$data = array(
	'id'			=>	'album_id',
	'name' 			=> 	'album_name',
	'author'		=>	'author_name',
	'genre_id'		=>	'genre_id'	
);
	

The query in the get_list method retrieves all the albums rows.

		$this->db->select('albums.id as id,albums.name as name,albums.author as author, genres.name as genre');  
		$this->db->from($this->album_table);  
		$this->db->join($this->genre_table,'genres.id','albums.genre_id');
		$query = $this->db->get();
		return $query->result_array();
	

Now, the genre model. Create a file called genre.php in application/models/ and paste the code below it:

	<?php defined('SYSPATH') OR die('No direct access allowed.');

	class Genre_Model extends Model
	{
		private $genre_table;
	
		function __construct()
		{
			parent::__construct();
			$this->genre_table = 'genres';
		}
	
		function get_list()
		{
			$query = $this->db->get($this->genre_table);
			return  $query->result_array();		
		}
	}
	

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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<?php
	echo html::stylesheet(array
		(
		 'assets/css/style'
		),
		array
		(
		 'screen'
		), FALSE);
?>
		<title>CD COLLECTION</title>
		</head>
		<body>
		<?php 
				echo html::image('assets/images/add.png');
				echo html::anchor('album/show_create_editor', 'Add new album'); 
		?>
		<table class="list" cellspacing="0">
		<tr>
			<td colspan="5" class="list_title">CD Collection</td>
		</tr>	
		<tr>
			<td class="headers">Album name</td>
			<td class="headers">Author</td>
			<td colspan='3' class="headers">Genre</td>
		
		</tr>	
		<?php
			foreach($albums_list as $item)
			{
				echo "<tr>";
				echo "<td class='item'>".$item->name."</td>";
				echo "<td class='item'>".$item->author."</td>";
				echo "<td class='item'>".$item->genre."</td>";
				echo "<td class='item'>".html::anchor('album/delete/'.$item->id,html::image('assets/images/delete.png'))."</td>";		
				echo "<td class='item'>".html::anchor('album/show_update_editor/'.$item->id,html::image('assets/images/edit.png'))."</td>";		
				echo "</tr>";
			}
		?>
		</table>
		</body>
		</html>
	

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.

Let's now create a file called create.php in application/views/.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<?php
	echo html::stylesheet(array
	(
	    'assets/css/style'
	),
	array
	(
	    'screen'
	), FALSE);
?>
<title>CD COLLECTION</title>
</head>
<body>
<?php echo form::open('album/create'); ?>
<table class='editor'>
<tr>
	<td colspan='2' class='editor_title'>Create new album</td>
</tr>
<?php
	echo "<tr>";
	echo "<td>".form::label('name', 'Name: ')."</td>";
	echo "<td>".form::input('name', '')."</td>";
	echo "</tr>";
	
	echo "<tr>";
	echo "<td>".form::label('author', 'Author: ')."</td>";	
	echo "<td>".form::input('author', '')."</td>";	
	echo "<tr/>";
	
	echo "<tr>";
	echo "<td>".form::label('genre', 'Genre: ')."</td>";	
	echo "<td>".form::dropdown('genre_id',$genres_list)."</td>";
	echo "<tr/>";
	
	echo "<tr>";
	echo "<td colspan='2' align='left'>".form::submit('submit', 'Create album')."</td>";
	echo "</tr>";
?>
</table>
<?php echo form::close(); ?>
</body>
</html>

The last but not the least is the update view. Let's create a file called update.php in application/views/.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<?php
	echo html::stylesheet(array
	(
	    'assets/css/style'
	),
	array
	(
	    'screen'
	), FALSE);
?>
<title>CD COLLECTION</title>
</head>
<body>
<?php echo form::open('album/update'); ?>
<table class='editor'>
<tr>
	<td colspan='2' class='editor_title'>Update album</td>
</tr>
<?php
	echo "<tr>";
	echo "<td>".form::label('name', 'Name: ')."</td>";
	echo "<td>".form::input('name', $name)."</td>";
	echo "</tr>";
	
	echo "<tr>";
	echo "<td>".form::label('author', 'Author: ')."</td>";	
	echo "<td>".form::input('author', $author)."</td>";	
	echo "<tr/>";
	
	echo "<tr>";
	echo "<td>".form::label('genre', 'Genre: ')."</td>";	
	echo "<td>".form::dropdown('genre_id',$genres_list, $genre_id)."</td>";
	echo "<tr/>";
	
	echo "<tr>";
	echo "<td colspan='2' align='left'>".form::submit('submit', 'Update album')."</td>";
	echo "</tr>";
	
?>
</table>
<?php 
	echo form::hidden('album_id',$album_id);
	echo form::close(); 
?>
</body>
</html>

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.

In the css folder create a new file called style.css and paste this:

a {
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif ;
	font-weight: normal;
	font-size: 12px;
	color: #00F;
	vertical-align:text-top;
}

img {
	border: 0;
}

label {
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif ;
	font-weight: normal;
	font-size: 12px;
}

input {
	border: 1px solid #000;
}

select {
	width:185px;
}

table.editor
{
	text-align: center;
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif ;
	font-weight: normal;
	font-size: 11px;
	color: #fff;
	width: 280px;
	background-color: #666;
	border: 0px;
	border-collapse: collapse;
	border-spacing: 0px;
}

table.editor td.editor_title
{
	background-color: #666;
	color: #fff;
	padding: 4px;
	text-align: left;
	font-weight: bold;
	font-size: 16px;
} 

table.editor td
{
	padding: 4px;
} 

table.list
{
	text-align: center;
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif ;
	font-weight: normal;
	font-size: 11px;
	color: #fff;
	width: 280px;
	background-color: #666;
	border: 0px;
	border-collapse: collapse;
	border-spacing: 0px;
}

table.list td.item
{
	background-color: #CCC;
	color: #000;
	padding: 4px;
	text-align: left;
	border: 1px #fff solid;
}

table.list td.list_title,table.list td.headers
{
	background-color: #666;
	color: #fff;
	padding: 4px;
	text-align: left;
	border-bottom: 2px #fff solid;
	font-weight: bold;
} 

table.list td.list_title
{
	font-size: 16px;
} 

table.list td.headers
{
	font-size: 12px;
}

Now copy the following images to the images folder:  

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.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Bogdan S. July 9th

    Very interesting. I will give it a try for sure. Thanks

    ( Reply )
  2. PG

    Felix Boyeaux July 9th

    I was hesitating between Kohana or CodeIgniter recently, but the OO philosophy of Kohana and the fact that CI works very poorly with PHP 5.3.0 helped me greatly with my decision.

    I’ve been using Kohana for two weeks now and I must say I love it! It’s great to see a tutorial about this framework.

    ( Reply )
  3. PG

    Levi July 9th

    About 98% of the time when working with Kohana, I want to murder something. It might be my general distaste for the lack of thought in PHP, or Kohana’s seemingly empty documentation, but whatever the case, you might want to double check your ambitions when using this framework.

    ( Reply )
    1. PG

      Lamonte July 13th

      I’m sorry, but if you really can’t use this framework to create “any” site and have “issues” with the framework, something is wrong.

      It’s the easiest, well documented, framework I’ve used along side CI. Let alone anything that you might have to ask about the framework that’s not in the docs a quick “forum” search does the trick every time.

      Maybe the payment library isn’t as “flexible” as I want it to be, the framework by itself is very good.

      ( Reply )
    2. PG

      Zoran July 14th

      I totally agree with you :D .. Kohana seems to be very easy to learn at first, but once you need something more complex then you are in trouble, cause you have to learn from the source code and it sucks so much.. If you are ready on wasting time take this framework… otherwise for beginners i would suggest CodeIgniter which has the best community out there

      ( Reply )
  4. PG

    djc July 9th

    quick question – I had looked into Zend but found it much too complicated for my needs. However, one of the tips/notes they had was that any application logic should be behind the public_html folder. It looks like Kohana has everything in the public area of the website… is that OK?
    By which, I mean, if I go to example.com/application/controllers I should be able to access the controller. With zend it was recommended to be something like
    root->public_html/index.php
    root->application/

    so that a person browsing the web would not have access to the application folder.

    Is this not a concern?

    ( Reply )
    1. PG

      anonymous cowherd July 10th

      this tutorial sets it up that way, but you’re free to put it outside of public_html so long as index.php is accessible and has paths set properly (as indicated by install.php.

      Also, pretty much all the files that come with kohana have a snippet at the top to die if it is accessed directly.

      ( Reply )
    2. PG

      Montana Flynn July 10th

      They probably take care of that server side, most likely with an .htaccess file.

      ( Reply )
    3. PG

      Rick July 10th

      The location of the system and application directories are configurable in the index.php bootstrap file. They are normally placed above the web root on production sites. You can use of the Kohana IN_PRODUCTION constant to conditionally set the location of those directories.

      ( Reply )
    4. PG

      tuntis July 10th

      It’s possible to have a folder structure like that with Kohana, too – and it’s recommended that you alter it in production environments.

      You’ll need to edit the index.php file to point to your application & system folders.

      ( Reply )
  5. PG

    Robert July 9th

    Thanks for the short tutorial.

    ( Reply )
  6. PG

    Andreas Eriksson July 9th

    Nice post, even though i never tried Kohana.

    I was also wondering which database-modeling application that was used to make the database screenshot? Anyone?

    ( Reply )
    1. PG

      Lars Hopman July 9th

      phpmyadmin and choose then designer

      ( Reply )
    2. PG

      Ed July 9th

      Andreas – I was wondering the same thing! I use toad datamodeler on my PC but can’t find anything like that for my Mac…

      ( Reply )
    3. PG

      Shaun July 9th

      It does not look the same, but MySQL workbench is great.

      http://dev.mysql.com/workbench/

      ( Reply )
      1. PG

        asdoaw July 9th

        isnt that phpMyAdmin?

    4. PG

      Scott July 9th

      Looks like PhpMyAdmin from what I can tell

      ( Reply )
    5. PG

      Teejay July 9th

      It was phpmyadmin… go to the designer tab when viewing the database.

      ( Reply )
    6. PG

      knoedel July 9th

      PHPMyAdmin ;)

      ( Reply )
    7. PG

      Cristian Gilè July 10th

      PHPMyAdmin database designer.

      Cheers

      ( Reply )
      1. PG

        Hossain July 10th

        you need phpMyAdmin version 3.x.x.x though. version 2.x.x probably doesnt have this feature.

  7. yeah, Kohana + Zend framework is a brilliant compilation
    great introduction, Kohana is a nice step forward when looking at Code Igniter, I used them both, but Kohana does not limit us as CI and I love this ‘freedom’

    thanks for the great article

    Maciej

    ( Reply )
  8. PG

    barat July 9th

    I use Kohana a little while … in this Project You could use some kind of Template controller extending Template_Controller to have default “body” of the webpage insteed of using render() in every single method :)
    Next thing is that You can use Formo module for form creating – it will validate Your input too :)
    And I prefeer just regular queryies than this Builder or ORM … maybe it’s oldshool :)

    ( Reply )
  9. PG

    Paul July 9th

    I was already to move my proprietary work to CodeIgniter but if Kohana is PHP 5 supported, well now I don’t know. Does anybody have an opinion on which is better? … more widely supported?

    ( Reply )
  10. PG

    eques July 9th

    well i’m used to program top-down, but since this is getting outdated i have desided to learn OO. Is this the framework for the newbie or not ?

    ( Reply )
    1. PG

      Jeremy Lindblom July 9th

      This is the first PHP Framework I have used, and it took me less than a week to figure out most of it. I recommend it, highly. It has improved our productivity and code reuse at work big time.

      ( Reply )
      1. PG

        eques July 10th

        is it ideal to learn OO with a framework, or fist OO alone?

      2. PG

        loonies July 14th

        @eques

        I suggest that you learn OOP concepts first.

    2. PG

      Hon tap July 9th

      I think this framework is easy for newbie. Just follow some tutorial like this post, we can make our own apps. Because Kohana is based on CI, you can take a look at CI for some tutorials (I think the number of tutorials for CI is bigger than for Kohana).

      ( Reply )
  11. PG

    Soner Gönül July 9th

    Liked!

    Follow this link for learning PHP
    http://www.sonergonul.com
    twitter.com/sonergonul
    friendfeed.com/sonergonul

    ( Reply )
  12. PG

    St0iK July 9th

    Great Tut ,thanx a lot!

    ( Reply )
  13. PG

    Robert July 9th

    Every time I see a framework reviewed I read it, but end up sticking to my stale old hand-written code. Maybe I am missing a very obvious point (and I assume I am, so please enlighten me), but it seems like a framework adds a lot of potential bloat.

    Take for example, the file structure screen shot shown in this tutorial. I look at that and run away. Yes it’s organized- but it’s like… micro-organized.

    ( Reply )
    1. PG

      Matthijn July 9th

      Dont know if you are familliar with the MVC model, seperation of data, logic and templates, therfore allmost all your work will be done in only three directorys, the models, views and controllers dir.

      Most of the hussle you would normaly need to program yourself, like connecting to the database, error page handling, neat urls, and many more (from sending mails to parsing PDF files) is done by verry little code because the framework has that code, and can be used with a few lines of code of your own.

      Allso, the structure is very logical once you understand why there has been chosen for a certain structure, remeber, thousands of people improve the open source frameworks every day, most likely someone thought of something you wouldnt, and that way improve the reusability and readabilty and productivity of the code.

      ( Reply )
    2. PG

      JimmyJames July 9th

      Agreed. I’ve been developing in PHP for eight years and haven’t had any needs to use a framework. I’ve seen a few and passed simply because the level of abstraction that they introduce seem totally unnecessary. Unfortunately I’ve had to program and debug a few apps that use frameworks and it’s been a messy and time consuming experience.

      BTW, do the tuts sites seem to be offline every day for a few minutes or is it just me?

      ( Reply )
      1. PG

        Nathan Ledet July 9th

        yeah…it happens for like 10 minutes and then works again…weird.

    3. PG

      TJ Koblentz July 9th

      Not to mention, you will ALWAYS have more organization with a mainstream framework. You never know where your project will take you. One of the advantages of using a framework is that if you ever end up adding members to your team or even deciding to get rid of it / expand, it will be much harder to do so when using code that is particular to you.

      Obviously, there are many more reasons for why using frameworks is a good idea (including enormous time / efficiency boosts as well many features that come in and out of the box, such as an instant base security, routing, etc… but also plugins and add ons if the framework is OS), I just don’t have the time and focus to go through them at the moment.

      ( Reply )
    4. PG

      Michael Irwin July 9th

      I’ve noticed that using frameworks takes the load off of me. If PHP was to update, or something else was to happen, I don’t have to worry about the code breaking because all frameworks are thoroughly tested before launch. I don’t know… just a personal preference.

      ( Reply )
      1. PG

        JC Reus July 10th

        I started life writing enterprise Java applications. With server-side Java, you’d be nuts not to use a framework to take care of all the nasty gobbly gook involved in writing applications for a platform as quirky and temperamental as the long-distance call/response system of HTTP.

        When I moved to PHP I brought this mindset with me. Framework was a must, or else I’d spend hours reinventing wheels and maintaining nightmarish spaghetti plates of code.

        I’ve found after a few years that this logic was flawed. Because Java, unlike PHP, is a compiled language. What this means is, after you’ve written all your code in Java using a nice robust framework, you compile that code and, thanks to the resource-saving brilliance of the Java compiler, all the bloat disappears.

        PHP doesn’t have this luxury, PHP is *interpreted* … meaning that every time somebody makes a HTTP request to one of your PHP apps, the entire bloat of the framework is read and essentially “compiled” on the spot.

        Both fortunately and unfortunately, PHP is a reactionary language that tries to be everything for everybody. PHP excels at small-footprint, rapid development types of applications.. but if you’re using a bloated coding framework, well.. I think you’ve missed the point, and possibly should look into using a platform that’s built for such a solution.

    5. PG

      Michele July 9th

      Same here, I never end up using a Framework. I tried a couple a few months back, but they didn’t really seem useful to me.

      ( Reply )
    6. PG

      Lee July 9th

      The biggest benefits of using a framework for me are (for example the symfony framework):
      - strict structure helps many developers work on the same project and know what’s where, why, what naming convention to use, etc. (also easier to update an older project where you know exactly how/why things work)
      - MVC makes me keep code clean and organized
      - symfony comes built in w/ database abstraction and OO db model
      - built in debuggers help out a lot.. they can quickly show # of db queiries, the queiries itself, html request, db results, even results from a function in your action file if you set it up the function that way
      - community developed/submitted modules you can plug/play in your project
      - built in html/php caching

      pointless features in a framework:
      - 95% of helpers :P .. esp when frameworks change the helpers name in each release… Also, a lot of the times normal HTML/php code is already ingrained in your head and just as easy to type out as the helpers…
      - rsync features built in….

      However, if you have a great system in place w/o a framework, and you can stick to it.. and there is no need to have multiple developers work on a project w/ you… and your custom framework can be put into place in an hour or two, you might be better off doing what your doing :)

      ( Reply )
    7. PG

      John July 10th

      Sheer # files != bloat. On a particular request only a few files are used at a time. The point of a framework is to provide as many pre-written, helpful components as possible. I never understand why people are looking for threadbare frameworks. What’s the point?

      Bloat comes in the form of over the top programming logic. For instance Ive heard in the zend framework, it takes a dozen files to write a Hello World page. That’s bloat.

      But ideally you do want a framework that has a library of ready-to-go components that you can tap into WHEN and IF you need them. Just by virtue of them being there doesn’t mean it’s “bloated’.

      Frameworks also organize code properly, abstract away DB access, provide better security and provide built in templating via the view. After you’ve already written plenty of hand coded apps it gets to be grunt work and a good framework will automate alot of that away for you WHILE maintining decent performance in the form of non-bloated lean code.

      ( Reply )
    8. PG

      Victor July 18th

      I totally agree @Robert. Lee’s suggestion seems the most pragmatic.

      After spending so much time writting the same code over and over, I just invested a few minutes to create an on-demand class loader and dump all my classes into single folder.

      Having mvc patterns mind mapped and the vanilla kit I created gets me cooking projects in a few days rather than weeks

      Yet, the allure of using a framework can be tempting when working with a large number of devs. Great tut and great input from everyone !

      ( Reply )
    9. PG

      Rafi B. September 27th

      @Robert, same here – until I found Kohana ! I always ended up writing and improving my small hand written frameworks, and when I found Kohana, with its community driven developers, I base my work on Kohana (v3) and its a blast + very productive! :)

      ( Reply )
  14. PG

    Yoosuf July 9th

    cool and its a good intro for the frm wk, i feel like this also can be added for PLUSS

    ( Reply )
  15. PG

    Thomas Menga July 9th

    Thanks for this tutorial… It’s been a long time we’re waiting for a Kohana tut in here… Kohana rocks !

    ( Reply )
  16. PG

    Joakim July 9th

    Hey mate, was just wondering. What software do you use to create the database relations? Any to recomend, windows preferably? =) Otherwise, love the site and I will read through the whole article very soon.

    ( Reply )
    1. PG

      Hossain July 10th

      phpMyAdmin 3.x.x.x was used. You can also use MySQL Workbench

      ( Reply )
  17. PG

    Brandon Hansen July 9th

    Kohana is an awesome framework. The good and the bad is that it is always changing. Great because it just keeps getting better. Bad because it makes you wonder if you can expect support on “old” versions.

    But the community is great and it has sped up our development like nothing before.

    Really looking forward to the new HMVC in 3.0!

    ( Reply )
  18. PG

    Nathan Ledet July 9th

    geez…even tutorials are bringing up MJ. *sigh*…

    ( Reply )
  19. PG

    TJ Koblentz July 9th

    This looks a bit sad after habituating myself with my relatively new and sexy lovers named Ruby and Rails.

    Still, nice tutorial.

    ( Reply )
  20. PG

    Diego SA July 9th

    Interesting!

    ( Reply )
  21. PG

    Masa July 9th

    Yii is better than Kohana :)

    ( Reply )
    1. PG

      Rafi B. September 27th

      It will be nice if you share _why_ you think that

      ( Reply )
  22. PG

    Myfacefriends July 9th

    looks kohana nice., very interesting…

    ( Reply )
    1. PG

      Lamin Barrow July 9th

      hmmmm

      ( Reply )
    2. PG

      Christian July 15th

      Just try it and see how cooool its is ;-)

      ( Reply )
  23. PG

    Azerty July 9th

    Would it be possible to have a tutorial on Zend & Doctrine?

    ( Reply )
  24. PG

    Mirek July 9th

    I was thinking about trying Kohana lately. Thank you for this article.

    ( Reply )
  25. PG

    NetChaos July 9th

    Wow at last Kohana is on Nettus, cheers to Cristian. Expecting more, especially tutorials on the Version 3 of Kohana which is nearing completion. http://v3.kohanaphp.com/

    ( Reply )
  26. PG

    Chris July 9th

    I’m glad there’s a similar framework to CI that’s updated with PHP5 OOP.
    I’ve used CI extensively before and found the lack of OOP features implemented for PHP4 compatibility frustrating.

    Of course, I also love the Zend framework :P

    ( Reply )
  27. PG

    yoshi July 9th

    I’ve been using kohana for 2 years now and really makes coding really easy

    ( Reply )
  28. PG

    Jônatan Fróes July 9th

    I love Kohana and CI…

    ( Reply )
  29. PG

    kjuzil July 9th

    ohhhhh.

    ( Reply )
  30. PG

    Pablo Impallari July 9th

    I’ve been using Kohana since version 2 and is great. I love it.

    ( Reply )
    1. PG

      Teejay July 9th

      It’s still version 2.x. K 3.0 is still beta at this time

      ( Reply )
      1. PG

        Pablo Impallari July 15th

        I mean since 2.1. We are at 2.3.4 by now (8 releases in between)

  31. PG

    Ding Dong July 9th

    getting abit sick of frameworks…

    ( Reply )
  32. PG

    Brian Temecula July 9th

    Kohana was my first framework, and I learned it by converting my site to use it. There were some nice things about Kohana, but I ended up changing my site to use CodeIgniter, and like CodeIgniter a little better because the community forum is more active, and the documentation is more up to date. I actually think that Kohana has great potential, and I donated to the project. You should too!

    ( Reply )
  33. PG

    BIakaVeron July 9th

    It seems very poor without ORM power ;)

    ( Reply )
    1. PG

      anonymous cowherd July 10th

      Kohana has ORM, the tutorial just didn’t use it, instead using the database query builder.

      ( Reply )
  34. PG

    Kishore July 9th

    Kohana may be my first framework in use, as i am figuring it now to use.

    I heard Kohana for the first time :( I believe i was too late…..

    Any way, thanks to nettuts for showing me the updated world

    ( Reply )
  35. PG

    Akiva Levy July 10th

    Huzzah for Kohana and a big thanks to you for helping spread the love and knowledge with this article.

    I spent a long time reviewing various frameworks a few years ago and settled on Kohana (and how happy I am!).

    Not only is it extremely important to note that Kohana is truly PHP 5 Object Oriented (why anyone would use a PHP 4 framework these days is beyond me), but the in-development Kohana3 is based around HMVC principals.

    ( Reply )
  36. PG

    Jonas De Smet July 10th

    Hi, I’m using Kohana but I dislike some code-techniques from you.

    - Isn’t it not better to copy the file “system/config/database.php” to “application/config/database.php” instead of overwriting it… So you can update the framework more easier…

    - Instead of doing everything with the query builder (like insert, delete, …) you should use the strenght of the ORM-capabilities that Kohana offers… Less coding and easier to understand…

    Just my 2 cents

    ( Reply )
    1. PG

      Cristian Gilè July 10th

      Hi Jonas,

      you are right but this is a an introduction to Kohana, and in a small article I can’t explain every aspect of the framework. New tuts coming soon.

      Thanks for your advices

      ( Reply )
    2. PG

      Felix Boyeaux July 10th

      I agree with you. There are some more flaws too:

      - Instanciating three views and two models in the constructor is a serious performance issue. Indeed, why have memory and CPU used for something that is not going to be used? Why instanciate the update view when only using the create view?

      - Calling the show_album_list() method in the index() method is useless… Why not just put the show_album_list() code in the index() method. This would make one less method and make your code easier to read.

      - sizeof() ? Come on! You should be using count()!

      Just a few details. Otherwise good tut.

      ( Reply )
      1. PG

        Bob July 22nd

        sizeof and count are identical.

  37. PG

    Ümit Ünal July 10th

    Nice article.Thanks.

    ( Reply )
  38. PG

    Gav July 10th

    Great Article! Although I like Kohana the Community behind it is no way near Codeigniter – hopefully they will one day have a community just as active as CI’s – that would make a true winner for me!

    ( Reply )
  39. PG

    Muhammad Adnan July 10th

    yeah , i will dig in Kohana Soon . Good Tut !

    ( Reply )
  40. PG

    JJenZz July 10th

    Oooh, I was trying to decide between CodeIgniter and Kohana recently too so this has come up at a good time.

    Bookmarked… I’ll be reading this later =) thx.

    ( Reply )
  41. PG

    Benjamin Reid July 10th

    Wow, this seems really powerful but simple. Great TUT also, it’s spot on, works to a tee.

    Good explanation of the code with people that might be new to PHP.

    ( Reply )
    1. PG

      Peter July 10th

      This tutorial does not really show how simple/powerful things can be with Kohana since it is (or appears to be) written by someone who doesn’t really know Kohana too well. It only gets slicker from here.

      ( Reply )
  42. PG

    mikaweb July 10th

    I use Kohana since one year and it’s a perfect framework for me. It makes everything I want easily.

    ( Reply )
  43. PG

    Aayush July 10th

    Still haven’t been able to get to use one framework, they all seem good but hand coding application with classic PHP seems great to me….plus it’s hard choosing between so many different frameworks especially when I don’t know the main differences….All the good one and most of the bad ones(as some say) use MVC design pattern….I really should choose one….people say good things about frameworks….

    any suggestions which one I should start using…? or which one is easier to start with…?

    ( Reply )
    1. PG

      Cristian Gilè July 10th

      Kohana?

      ( Reply )
    2. PG

      Benjamin Reid July 10th

      That’s what we need a comparison! A new article for NETTUTS.

      ( Reply )
    3. PG

      arnold July 10th

      “cough” CI…

      ( Reply )
    4. PG

      JC Reus July 10th

      Been wondering.. has anyone here used the Zend framework?
      I’ve heard it’s extremely lightweight.

      ( Reply )
    5. PG

      eques July 10th

      yes i couldn’t agree more, cause CI is written in PHP4 so there’s that ..
      cakePHP seems to have a good community, is it any good?

      ( Reply )
  44. PG

    Krystian July 10th

    Great tut. What do you think about Smarty !

    ( Reply )
    1. PG

      anonymous cowherd July 10th

      Smarty isn’t so much a framework as just a templating system. In fact, you can use Smarty for your Views if you like.

      Google around, someone even has kohana prepackaged with Smarty ;)

      ( Reply )
  45. PG

    Jason Wilson July 10th

    Obviously there was something about Code Igniter that the Kohana folks thought they could do better. Anyone know what it is or if they succeeded.

    CI was the first PHP framework I ever liked and so far has been working great for me. Anyone used both who can tell me, is this ‘just another framework’ or should I be interested?

    ( Reply )
    1. PG

      Felix Boyeaux July 10th

      Well the main thing the Kohana team thought they could do better was to drop PHP4 compatibility and make the source code 100% strict OOP. This is why I prefer Kohana over CodeIgniter, since they are very similar on all other things.

      ( Reply )
    2. PG

      loonies July 10th

      I have been using Codeigniter on 2 projects and switched to Kohana a 1.5 years ago. Things I love in Kohana compared to Codeigniter.

      - Community driven

      - Faster development cycle

      - Strict OOP and all benefits that it brings

      - Application folder outside the system folder. When upgrading, no need for gymnastic training and braking neck.

      - Native modules support. No need for surgery.
      a) CI way
      You have to put each of libs, helpers into corresponding folder.
      b) Kohana way
      You have drop-in modules already prepared. All comes to copy/paste module containing all libs, helpers, etc.

      - Cascading architecture
      Take a look here: http://upload.wikimedia.org/wikipedia/en/1/1c/Kohana-modules.png

      - Events
      Take a look here: http://docs.kohanaphp.com/general/events

      - Better error handling through exceptions

      - Avoids collision between controllers and models naming

      - Views represented as object

      - ORM

      - More powerful libraries. I specially like advantages of validation lib

      - Native library drivers support.
      Take session library. You can choose among several storages (cookie, database, native php, …) accessing them with the same API.

      - Resources loading (libs, helpers, controllers, models, etc)
      a) CI way
      I have to do garbage like this

      $this->load->library(’lib1′, ‘lib2′, …);
      $this->load->helper(’help1′, ‘help2′, …)
      $this->load->model(’User_model);

      $this->lib1->method1(arg1, arg2, …);
      $this->lib2->method1(arg1, arg2, …);

      helper_function1(arg1, arg2, …);
      helper_function2(arg1, arg2, …);

      $this->User_model->method1(arg1, arg2, …);

      // If I make my own lib, even more garbage introduced
      $CI =& get_instance();
      $CI->load->library(’somelib’);
      $CI->load->helper(’help1′);
      $CI->config->load(’my_lib_config’);

      $result = $CI->somelib($CI->config->item(’my_lib_config_item’));

      b) Kohana way, nice and clean
      $obj1 = new lib1;
      $obj2 = new lib2(arg1, arg2);
      $user = new User_Model;

      $obj1->method1(arg1, arg2, …);

      $obj3->factory()->method1(arg1, arg2, …);
      $obj4->instance()->method1(arg1, arg2, …);

      $user->method1(arg1, arg2, …);

      // Helpers, without any special loading before using
      helper::function1(arg1, arg2, …);

      ( Reply )
      1. PG

        Hieu Vo July 10th

        Haha, the way you use the word “garbage” is really funny :) )
        In fact, I have used neither CI nor Kohana, but after reading your comment I think I’ll try Konaha first ; )

      2. PG

        Mark Jones July 13th

        Just thought I’d point out that you CAN remove your application folder from your system folder when working with CI.

      3. PG

        loonies July 14th

        With CI you can remove your application folder somewhere, but with Kohana this is native and by my viewpoint it’s more logical and “natural”.

  46. PG

    Duane July 10th

    Has anyone used this as well as symfony (http://www.symfony-project.org)? I would be interested in hearing thought about how they compare.

    I do a good deal of symfony development and it seems that the symfony framework automates a lot of the model generation. Does Kohana have generators to produce this? I’ve found this feature in symfony to be immensely helpful as my database design evolves in a project.

    ( Reply )
    1. PG

      loonies July 14th

      There is no bash shell scripts for code generation in Kohana.

      But for models you would do something like this, using ORM:

      create file “user.php” under modules directory with following content:

      class User_Model extend ORM {}

      Take a closer look: http://docs.kohanaphp.com/libraries/orm

      ( Reply )
  47. PG

    neovive July 10th

    I’ve been using Kohana for the past year and it’s an excellent framework. Spend some time reading the docs, forums and review the sample code available in the module repository. There are also some open source Kohana applications (e.g. Gallery3 and Argentum Invoice) that you can download to review.

    There is also a good Kohana 101 tutorial (http://forum.kohanaphp.com/comments.php?DiscussionID=1144&page=1) available on the forums.

    ( Reply )
  48. PG

    Gabe July 10th

    Any one else run this tutorial and get an error when trying to update an album? When I click the “edit” icon, I get:
    “An error was detected which prevented the loading of this page. If this problem persists, please contact the website administrator.

    application/controllers/album.php [43]:

    Undefined property: stdClass::$id”

    Did I miss something? Any clues how to resolve that?

    ( Reply )
    1. PG

      Gabe July 10th

      Nevermind, I figured it out – MySQL is case sensitive, dummy…

      ( Reply )
  49. PG

    Mohammed July 10th

    How about Yii? i think it’s faster than konna and it’s well-documented!

    ( Reply )
  50. PG

    Another Flava July 10th

    Do not waste your the new version of kohana which is in beta is completely rewritten each successive major version of kohana is not compatible with the last.

    The lead dev in particular is very rude and it definitely not community driven…

    ( Reply )
  51. PG

    Gafitescu Daniel July 10th

    I see it is very similar to CodeIgniter

    ( Reply )
  52. PG

    Ethan July 11th

    Very cool! I will be sure to try this. And it has some very in-depth documentation.

    (I can’t help but notice you misspelled Michael)

    ( Reply )
  53. PG

    Steve July 11th

    Wow, this seems realy good. Very light weight.

    I am currently using Symfony (due to my current job and am quite liking it) but this seems much lighter. I had begun to use cakePHP, when I first got in to php OOP, which also seems good. I found cake very good as a beginner to OOP.

    I intend to focus on Kohana for the time being as it seems very simple.

    ( Reply )
  54. PG

    Andreas Andreou July 11th

    Coming from the java world and having used Kohana for the last 5-6 months, i only have good words to say for it.

    I18N is another of its strong points but basically its simple and clean MVC will get you up and running from the first minute.

    There are a few tricks you can use that i haven’t seen documented (like using multiple views/view fragments to compose the full result – sort of like the component-based frameworks in java, i.e. tapestry, jsf) but this should improve over time

    Eagerly waiting for v3.0

    ( Reply )
  55. PG

    Calum MacLeod July 11th

    I had been learning kohana for a few weeks with some help from the patient folk at #kohana on freenode. I had also tried a tutorial called Kohana 101, which was a good place to start. However, this tutorial on making a CD Collection, listing albums, updating the list and deleting items has been a further revelation. I have benefitted from both tutorials. The first laid the groundwork and this latter has show what is possible for someone such as myself who is not a programmer and has limited knowledge, ability and insight. Some of us who dabble as a hobby in php and general computing need as much help as we can get and we need to examine good and orderly examples of code that works. The clarity of the presentation in this tutorial is very impressive.

    (The only downside that I shall mention was that that the copy to clipboard function seemed to keep copying the same file to my clipboard and I had not realised until I had copied the whole lot ! However, not everyone will be as dozy as I am and would notice earlier that it was not working for them. Indeed, it might be some lack of expertise on my part that caused it not to function as it ought. If you find you have error messages complaining of redeclaring classes, it may well be that you too have fallen foul of this problem. )

    I wish all tutorials could be as clear, informative and helpful as this one.

    ( Reply )
  56. PG

    Soner Gönül July 12th

    Great ;)

    ( Reply )
  57. PG

    exiled July 12th

    My CSS style sheet is no tbeing applied. I have created an assets/css directory and its not working. Can someone explain to me how to get it work and also the images directory too.

    ( Reply )
    1. PG

      Cristian Gilè July 13th

      Have you created the assets folder in the right place?

      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.

      Kohana root
      |
      |__application
      |
      |__assets
      | |
      | |__css
      | |
      | |__images
      |
      |__modules
      |
      |__system

      You can view the generated HTML code and check the href attribute of the link tag to solve this issue.

      ( Reply )
  58. PG

    sumit mukhia July 12th

    wowwwwww..i’ll give it a go tonight…..thanks again for an amazing tutorial..

    ( Reply )
  59. PG

    Nick July 13th

    Vary good framework I see!!

    ( Reply )
  60. PG

    DemoGeek July 13th

    I’ve been developing a simple site with CodeIgniter. Initially it was a bit exciting to see we can get things done pretty quick but then it died-down on me because of the lack of OO as I come from OO background. Kohana seems to fill that gap and might have my business if they can spread out some more detailed documentation similar to the way CI has their documentation.

    ( Reply )
  61. PG

    Senthil Kumar July 13th

    Nice Article.
    I’ve already tried kohana before 2 months.
    I am using CodeIgniter Now.
    May be, I’ll go back .

    Senthil Kumar
    designfellow.com
    @designfellow

    ( Reply )
  62. PG

    Lamonte July 13th

    For a beginner KohanaPHP user sure you can follow this tut. No one uses the “set” method for views anymore.

    Your:
    $this->update_view->set(’album_id’,$album_data[0]->id);

    Easily could be redone like:
    $this->update->view->album_id = $album_data[0]->id;

    Also you used sizeof() to count the amount?

    Dude thats a waste of time since theres a built in “count()” method for the Query Builder …

    if(sizeof($db_genres_list) >= 1)

    Should be:

    if($db_genres_list->count() >= 1)

    ( Reply )
    1. PG

      Zamshed Farhan November 1st

      Thanx Lemonte. Very helpful information u gave.

      ( Reply )
  63. PG

    Miles Johnson July 14th

    The whole structure and procedure of this framework is wrong. Why do you have to initialize everything yourself? The point of a framework is to make it easy for your and to do it automatically.

    No other framework seems to get it right except CakePHP or Symfony.

    ( Reply )
    1. PG

      loonies July 14th

      I would dissagree at this point with Miles Johnson.

      The point of framework is to alleviate with common activities performed in development, like DB access, data validation, session management, etc.

      Personally I prefer to have control over application execution.

      ( Reply )
      1. PG

        Christian July 15th

        I think Miles using Cake and Symfony that why he is asking……..
        Not ready to learn new method and techniques ;)

        100% agreed with loonies,

        Great Tutorial.

      2. PG

        Miles Johnson July 15th

        I disagree with you, that is what libraries and classes are for.

        Not a framework.

        A good percentage of people who work in PHP do it procedurally wrong, and with browsing Kohana, they do it wrong.

      3. PG

        Rafi B. September 27th

        Agree with loonies. I messed around with all the popular frameworks, and decided Kohana is the best way _for me_ to go. Total control of your application, great ORM module, perfect hierarchy, it’s really for serious coders who know what their doing. All in all, perfect framework in my opinion.

  64. PG

    Zoran July 14th

    Lack of documentation makes this framework sucks so much… Anyway thanks for the tutorial

    ( Reply )
  65. PG

    acul July 15th

    Wow.. great tutorial. I have to try and make me falling in love with Kohana. thanks

    ( Reply )
  66. PG

    arturas July 15th

    thanks for tut! hope read yours tuts in future!

    ( Reply )
  67. PG

    damian July 19th

    Good job.
    It is what I looked for, thanks.

    ( Reply )
  68. PG

    Chris Simpson July 23rd

    Fantastic stuff. the Kohana / CI choice at work is approaching so ill be sure to look closely at this.

    ( Reply )
  69. PG

    Althalos July 26th

    I really like this framework. I’ve been taking a closer look at it for the past couple of days and it seems really great. Good article too, I like how it’s written and what it brings up… but, alas, I can’t get it to work. For some reason it won’t use my config file with my mysql-info, instead it uses the default user and password (dbuser/p@assword).

    ( Reply )
  70. PG

    Kamal El Fatihi July 26th

    Westing lotse of time

    lots lots of time to just dowing that !!

    im not agree with any of the php framworks as Rasmus said .

    ( Reply )
  71. PG

    ahmad July 31st

    gr8 will giv it a try

    ( Reply )
  72. PG

    Althalos July 31st

    Um.. just wanna say I eventually figured my problem out (read two posts above). It might help anyone to know that at the top of database.php there’s supposed to be a <?php .. or at least that’s how I got it working.

    ( Reply )
  73. PG

    Jimmy August 4th

    Hmm… seems so complicated to me.. I saw DooPHP the other day. That’s a whole lot easier than this tutorial. If any newbies like me are interested.
    http://doophp.com

    ( Reply )
  74. PG

    memati September 2nd

    i get this error:
    Fatal error: Class ‘Genre_Model’ not found in C:\AppServ\www\kohana\application\controllers\album.php on line 16

    ( Reply )
  75. PG

    Ste September 22nd

    Great, thanks. I’ve just started to develop with a framework. I hope to see more kohana tuts here. ;)

    ( Reply )
  76. PG

    Rafi B. September 27th

    +1 Kohana. v3 is awesome!!!

    ( Reply )
  77. PG

    Maxwell October 3rd

    Great tutorial dude!
    I’ll definitely peek back once I dig into Kohana. It’s amazing how far PHP has come over the past 10 years — really. Heck, LAMP (Linux, Apache, MySQL, PHP) kicks ass!! And best of all, it’s frigging FREE!

    Cheers!

    - MaxTheITpro

    ( Reply )
  78. PG

    Zamshed Farhan November 1st

    It is the most great tutorial to learn Kohana for beginners.

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    November 1st