Kohana is the framework I liked best among other PHP framework. Its an easy one also
. To me it is organized, highly object oriented, having clear separation of model, view & controller. Autoloading of classes is nice feature here also. Here is the tutorial I prepared. In a simple and short…
- It is going to be a 3 or 4 part series
- All series will have around 10+/- steps
- I will be creating a simple blog with this example
Probably you have downloaded the zip file from here. Below are the steps one by one. So lets start…
Installation
- Extract the zip file in htdocs folder
- Rename it to kohana-blog
- Now hit the url: http://localhost/kohana-blog/
- You should see your installation info
- If you are using linux, make kohana-blog/application/logs & kohana-blog/application/cache folder writable
- You are done
Initial configuration
- Now remove/rename kohana-blog/install.php.
- Change kohana-blog/application/bootstrap.php as same as below.
Kohana::init(array( 'base_url' => '/kohana-blog', ));
- Now try accessing any of the URLs listed below
Get introduce with action & controller
By default URL format for koahna is like http://<base_url>/index.php/<controller>/<action>. So for an example http://localhost/kohana/index.php/article/new means it will be looking for article controller (Controller_Article) and execute new action (action_new()). If action part is empty, index action will be executed
.
- controller & action in Kohana:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Welcome extends Controller {
public function action_index() {
$this->response->body('hello, world!');
}
} // End Welcome
- Here Controller_ is the prefix for welcome controller & it extends Controller
- Here action_ is the prefix for an action
- $this->response->body(‘hello, world!’); sets hello, world! as the response for the request.
- Lets add an action as highlighted below
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Welcome extends Controller {
public function action_index() {
$this>response->body('hello, world!');
}
public function action_another() {
$this->response->body('added another action...');
}
} // End Welcome
Now try this url: http://localhost/kohana-blog/index.php/welcome/another
- Lets create an article controller for our blog as below.
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Article extends Controller {
public function action_index() {
$this->response->body("Kohana Blog");
}
}
Now try this url: http://localhost/kohana-blog/index.php/article/index
Render a view with Kohana
- Create the kohana-blog/application/views/article/index.php file under application/view folder as shown below
<?php defined('SYSPATH') or die('No direct script access.'); ?>
<h1>Kohana Blog Homepage</h1>
- Modify the Controller_Article‘s method action_index() as below to load the view
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Article extends Controller {
public function action_index() {
$view = new View('article/index'); // loads the 'article/index.php' file under 'application/view' folder
$this->response->body($view); // render the view as response
}
}
Now try this url again: http://localhost/kohana-blog/index.php/article/index
Now prepare database configuration
- Run following sql script. It will create simple articles table in the database.
CREATE SCHEMA `kohana_blog`; use `kohana_blog`; CREATE TABLE `kohana_blog`.`articles` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) DEFAULT NULL, `content` text, PRIMARY KEY (`id`) );
We will use Kohana ORM to communicate with database. So both database & orm module is needed to be enabled. we can do so modifying kohana-blog/application/bootstrap.php as shown below.
/** * Enable modules. Modules are referenced by a relative or absolute path. */ Kohana::modules(array( // 'auth' => MODPATH.'auth', // Basic authentication // 'cache' => MODPATH.'cache', // Caching with multiple backends // 'codebench' => MODPATH.'codebench', // Benchmarking tool 'database' => MODPATH.'database', // Database access // 'image' => MODPATH.'image', // Image manipulation 'orm' => MODPATH.'orm', // Object Relationship Mapping // 'unittest' => MODPATH.'unittest', // Unit testing // 'userguide' => MODPATH.'userguide', // User guide and API documentation ));
Create the kohana-blog/application/config/database.php configuration file under kohana-blog/application/config folder like as below. Change username & password accordingly.
<?php defined('SYSPATH') or die('No direct access allowed.');
return array
(
'default' => array
(
'type' => 'mysql',
'connection' => array(
'hostname' => 'localhost',
'database' => 'kohana_blog',
'username' => 'root',
'password' => 'root',
'persistent' => FALSE,
),
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
'profiling' => TRUE,
)
);
Congratulation!!! You are done with configuring your database.
Create a model
It is just easy. Create a article.php file under application/classes/model as shown below. Here, our Model_Article object extends ORM. By default it will assume table name from the model name (so cool). For article model table name is be articles. You can also change it, using $_table_name property. But this is not important now.
<?php defined('SYSPATH') or die('No direct script access.');
class Model_Article extends ORM {
}
This step is just easy, huh? We have few more steps to play with this article model.
Create the form to create/edit an article
Create a view file kohana-blog/application/views/article/edit.php under application/views folder as shown below.
<?php defined('SYSPATH') or die('No direct script access.'); ?>
<h1>Create new article</h1>
<?php echo Form::open('article/post/'.$article->id); ?>
<?php echo Form::label("title", "Title"); ?>
<br />
<?php echo Form::input("title", $article->title); ?>
<br />
<br />
<?php echo Form::label("content", "Content"); ?>
<br />
<?php echo Form::textarea("content", $article->content); ?>
<br />
<br />
<?php echo Form::submit("submit", "Submit"); ?>
<?php echo Form::close(); ?>
- Create new action to load the form
- Create post action to post & save the article
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Article extends Controller {
public function action_index() {
$view = new View('article/index');
$this->response->body($view);
}
// loads the new article form
public function action_new() {
$article = new Model_Article();
$view = new View('article/edit');
$view->set("article", $article);
$this->response->body($view);
}
// save the article
public function action_post() {
$article_id = $this->request->param('id');
$article = new Model_Article($article_id);
$article->values($_POST); // populate $article object from $_POST array
$article->save(); // saves article to database
$this->request->redirect('index.php/article'); // redirects to article page after saving
}
}
Now hit the url: http://localhost/kohana-blog/index.php/article/new and try creating some article.
Show list of articles
Lets improve our view to show all the articles.
- Load all the articles. It is shown below changing article’s index action.
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Article extends Controller {
public function action_index() {
$articles = ORM::factory('article')->find_all(); // loads all article object from table
$view = new View('article/index');
$view->set("articles", $articles); // set "articles" object to view
$this->response->body($view);
}
....
- Change article/index.php as below to load all the articles.
<?php defined('SYSPATH') or die('No direct script access.'); ?>
<h1>Kohana Blog Homepage</h1>
<?php echo HTML::anchor("article/new", "New Article"); ?>
<?php foreach ($articles as $article) : ?>
<div style="background-color: #dddddd; margin: 0px 2px 0px 2px">
<h2><?php echo $article->title; ?></h2>
<pre><?php echo $article->content; ?></pre>
<?php echo HTML::anchor("article/edit/".$article->id, "Edit"); ?>
<?php echo HTML::anchor("article/delete/".$article->id, "Delete"); ?>
</div>
<?php endforeach; ?>
Now hit the url: http://localhost/kohana-blog/index.php/article/index to see all created articles.
Update & delete an article
You can skip it, but this is to add the final touch of this part. Two more actions, edit & delete action, are added to the article controller.
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Article extends Controller {
const INDEX_PAGE = 'index.php/article';
public function action_index() {
$articles = ORM::factory('article')->find_all(); // loads all article object from table
$view = new View('article/index');
$view->set("articles", $articles); // set "articles" object to view
$this->response->body($view);
}
// loads the new article form
public function action_new() {
$article = new Model_Article();
$view = new View('article/edit');
$view->set("article", $article);
$this->response->body($view);
}
// edit the article
public function action_edit() {
$article_id = $this->request->param('id');
$article = new Model_Article($article_id);
$view = new View('article/edit');
$view->set("article", $article);
$this->response->body($view);
}
// delete the article
public function action_delete() {
$article_id = $this->request->param('id');
$article = new Model_Article($article_id);
$article->delete();
$this->request->redirect(self::INDEX_PAGE);
}
// save the article
public function action_post() {
$article_id = $this->request->param('id');
$article = new Model_Article($article_id);
$article->values($_POST); // populate $article object from $_POST array
$article->save(); // saves article to database
$this->request->redirect(self::INDEX_PAGE);
}
}
Now you can edit/delete an article also.
So this is it. I have tried to demonstrate the followings here
- Configure an kohana application
- Create a controller & action in kohana
- Render view in kohana. Thogh this is pretty basic concept.
- Working with ORM model
- CRUD (create, read, update & delete) operation using Kohana ORM
Let me know what do u think. Any kind of suggestion is appreciable.
Downloads: https://bitbucket.org/kowsercse/kohana-blog
Part 2: Kohana Tutorial: Part 2
Nice writeup bro, continue the series!
Thanks a lot
Ah … what a great tutorial for the KOHANA beginners! I am so inspired that just jumping inside KOHANA with the help of this series
don’t just jump, bring the ladder too
ya great step dude!! hope it will be really a helpful one.
Its really helpful tutorial for beginners like me.
Cheers for the article,
Perfect for a beginner like me.
Look forward to more
This is one a great tutorial as a quick start. Hope, you’ll continue the series. Best of luck.
good examples,thanks for your work.
Thank you for the great tutorial. I have been learning codeigniter over the past few weeks and having issues getting community written extensions not built in to work right and thought I’d give kohana a try since it is already set up for HMVC. I spent a couple of hours not finding any good tutorials for kohana and was about to give up hope until I found your site.
Thank you very much.
Glad! that you found it helpful.
I would love to write something on HMVC & Kohana.
Big thanks! I think it’s the best tutorial for Kohana beginners on the Internet. It’s easy to read, up-to-date and shows how to use ORM and Helpers. I learned a lot from this tutorial.
However, I think some little improvements can be made (to make it even better):
Thanks!
1. “Now remove/rename kohana-blog/installation.php” – install.php
2. “Change kohana-blog/bootstrap.php as same as below” – kohana-blog/application/bootstrap.php
3. If you rename “example.htaccess” to “.htaccess” you can access controllers as “kohana-blog/welcome” (not “kohana-blog/index.php/welcome”)
4. There’s no need to specify the size of `id` INT while creating table (http://j.mp/t5HpzV). You should also make it UNSIGNED to double the maximum value (I personally think that MEDIUMINT UNSIGNED is enough in most cases)
5. You can copy “database.php” from “modules\database\config\” and edit it (not create yourself)
6. In action_post(): is it necessary to send $article_id to Model_Article()? Using debugger I found that “$article_id = null” while creating new article. I also made a test with “$article = new Model_Article();” and it worked.
7. Please make a link to “Part 2″ clickable
Sorry, I was wrong with point 6. Function action_post() is completely okay. If you don’t pass $article_id you won’t be able to edit the article (it will add new articles instead of editing).
Glad to have a such a constructive feedback.
I will do so as recommended and wish to inform you.
Update: I have done it.
Great tutorial, helped me a lot by getting started in MVC
Thanks for posting this.
[...] Tutorial on kohana for the beginners. PHP Read the original post on DZone… [...]
[...] his blog today Kowser introduces you to Kohana, an easy to use, lightweight PHP HMVC framework that can help you get applications up and running [...]
Nice and easy tutorial. Just a note, you’re populating the article fields directly with $_POST. Might be a good idea to at least give a note that this is not the safest way of doing things. I haven’t read the other articles yet, so I’m not sure if you’re covering this already
Best/better practice is to use Arr::extract to get just the fields you need out of the $_POST:
$article->values(Arr::extract($_POST, array(‘title’, ‘content’)); // populate $article object from $_POST array
instead of:
$article->values($_POST); // populate $article object from $_POST array
Agreed and thanks a lot for your suggestion.
I wrote my first module with this article.
Passing to the second lesson…
Thanks.
Hi all! Thanks for this great tutorial.
Do you know a way to implement RSS feeds?
Thanks!
M.
Hi Kowser,
I am new to php and kohana. Got a probably pretty silly question – when I go to http://localhost/kohana_blog, the page shows hello, world, which is the function action_index in the Controller_Welcome class. The article.php also contains a action_index function in the same folder, why does the action_index in the Controller_Welcome class get executed and not the one from Article?
Thanks!
Kelly
[...] Kohana Tutorial: For the beginners | faded speech Kohana is the framework I liked best among other PHP framework. Its an easy one also . To me it is organized, highly object oriented, having clear separation of model, view & controller. Autoloading of classes is nice feature here also. [...]
Hi all!
First of all I would like to thank you for this good tutorial. However I encounter a problem where kohana framework add prefix to table name and prompt me error such as below:
Database_Exception [ 1146 ]: Table ‘kohana_blog. article’ doesn’t exist [ SELECT ` article`.* FROM ` article` AS ` article` ]
Hope anyone can help me on this. I’m figuring out why kohana add prefix which is single quote to table name, the table name appear as ‘article’ instead of article.
Hey man!
Looks like there is a blank space ” ” before your table name. You may wanna check it in your configuration in /application/config/database.php. Table prefix should be ‘table_prefix’=>”
@gladys
Sorry for being so late.
Can you give me the full stack trace?
You can also check @rami’s suggestion.
Thanks for your feedback.
Thanks a lot, man!
I’ve got just a tiny little remark on the “Create a model” step above:
The file mentioned – ‘article.php’ – should be in folder ‘/application/classes/model/’ not in ‘/application/model/’. At least that’s how it worked for me (version 3.2).
@rami: Updated. And many many thanks.
thanks ….this is where i locate for
Thanks…
[...] bir yorum yapamayacağım. Bu kaynaklarda daha detaylı bilgiye ulaşabilirsiniz : [1] – [2] – [...]
Good write up though I am having a tiny issue. When editing an article a new article is being created instead of updating the selected article. I know that the article is being selected because the form populates all the fields. Any quick fix on why its creating new articles instead of modifying the current one?
NM I figured it out. I forgot to add $player->id to the form method.
I had Form:open(‘article/post’); instead of Form::open(‘article/post/’.$article->id);
This is a very nice tutorial for a kohana beginer like me. I’ve also seen part 2 and it is very helpful and i’m wondering if you could help me with kohana 3.2 auth module. The documentation that I’ve found on other sites is not helpful at all. Thanks and have a nice day.
Simply Awesome!
The best beginner practical tutorial!…you should make more publications..
Really Its an worth able tutorial for any developers!…Thanks a lot Kowser
[...] basic Tutorial Like this:LikeBe the first to like this [...]
Thanks a lot Kowser, It really helped me a lot.
Thanks Kowser, it really helped me to understand the framework.
[...] I’m running Kohana v3.2 I’m just trying to get up and running with a small MVC and was recommended this system. I’m following this tutorial: http://kowsercse.com/2011/09/04/kohana-tutorial-beginners/ [...]