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
Can you get me example program of kohana using modules.
but actaully it was long jump not a high one……..:p
ya great step dude!! hope it will be really a helpful one.
if u any doubt means cantact me
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.
3) leaving .htaccess out of it might be useful for newbies by removing one more layer that can go wrong
though you are absolutely correct
[...] 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.
I know I am so late. But u may take a look at this very old answer in SO: Kohana 3 auth module, how to configure user table and fields
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/ [...]
Thank you for the very helpful tutorial, it was very useful and I learned a lot about Kohana.
I’m from Venezuela, and that makes it difficult to fully understand articles in another language than mine, but I assure you that of all the tutorials I’ve followed your beam was the best I mean even when in another language ..! helped me understand a lot of MVC, I hope you upload new tutorials of this MVC
Thanks a lot Kowser. This is one of the best tutorial available at present. Waiting for more posts!
Greatfull Tutorial, tanx.
but i have a question, i dont undrestand why we must passed the id as a parameter to
the new action ? @ this moment we dont have any record in table, what this id specify exactly ?
Yes, fully agreed that the “id” was not needed to be passed while creating an article.
I am just reusing the “edit.php” for for creating the creating. But surely it is not included with the post URL since “$article->id” is null.
The good practice is to have different action+view for create & edit. I have created the action but not the view.
Thanks for pointing it out.
Nice Article. Very helpful.
Thanks a lot.
Thank you for the very well written tutorial on the Kohana framework. I have dabbled with the framework in the past, but I never had a good grasp prior to your tutorial.
Is it good practice to use ORM in controllers or should we use Model Class?
e.g. $articles = ORM::factory(‘article’)->find_all(); in Controller_Article Above.
Thanks
RSVP
In my opinion, it is not a good practice to use ORM in controller. They should be hidden in service/business object call.
controller->service->dao/orm.
Consider above article just as a tutorial. Not to explain all these high level abstraction
Best article on Kohana available on net…
keep up the good work…
Hi Sanyam,
Hru? after long time..
Hey could you please answer my about query if u kno kohana well?
Great tutorial for beginners , thanks a lot.
Hi guys, after posting a new article it is successfully saved to the database but when the application tries to redirect to the index page i get the following error:-
ErrorException [ Fatal Error ]: Call to undefined method Request::redirect()
Please help
As a retired, non-technical professor looking to learn something new, I found this tutorial to be outstanding. Any suggestions would be self-serving I am sure. Keep up the good work. I am looking forward to the 2nd tutorial.
I am honored. And thank you.
Hi,
I tried to replace some code to see what happens nad I was hoping to get the same results but I didnt.
thats the factory method:
public static function factory($model, $id = NULL)
{
// Set class name
$model = ‘Model_’.$model;
return new $model($id);
}
And…
$articles = ORM::factory(‘article’)->find_all();
I replaced with:
$articles = new Model_Article();
$articles->find_all();
No error but I get no articles either, just “Kohana Blog Homepage” title and “New Article” link.
What is diffrent?
When deleting an article, I get the following error.
public function action_delete() {
47 $article_id = $this->request->param(‘id’);
48 $article = new Model_Article($article_id);
49
50 $article->delete();
51 ****** $this->request->redirect(self::INDEX_PAGE); ******
52 }
53
54 }
note: asterisks are mine to indicate the line error
Thank you for any help.
Problem solved changed error line to
$this->request->redirect(‘index.php/article’);
instead of
$this->request->redirect(self::INDEX_PAGE);
Really nice tutorial – was looking it for a long time. Really nice job – ty for help
ErrorException [ Fatal Error ]: Call to undefined method Request::redirect()
why its mot redirecting to my article page.???
I had the same problem and I solved it by replacing>
$this->request->redirect(self::INDEX_PAGE);
with>
HTTP::redirect(self::INDEX_PAGE);
Hope it helps!
Or just:
HTTP::redirect(‘article’);
if not using index.php
Concerning the redirection, since the new update of Kohana, you need to use the new syntax :
const INDEX_PAGE = ‘article’; // just give the name of Controller that we need it, otherwise the path will be : http://localhost/index.php/index.php/article
$this->redirect(self::INDEX_PAGE);
or just it if you don’t want to use a const :
$this->request->redirect(‘article’);
instead of
$this->request->redirect(self::INDEX_PAGE);
May God bless you for this really helpful tutorial!
i want update program example for php
Thank you for another wonderful article. Where else could anybody get that kind of info in such an ideal way of writing? I have a presentation next week, and I am on the look for such info. podkaszarki elektryczne http://www.twoje-strony.pl/al-ko-kober-sp-z-o-o-kosa-spalinowa-s-560.html
Nice tuttorial for bigginers just like me more of the same would really be appreciated if its okay maybe some attachments of the same etc. thankyou
wow, this article was SOOO helpful. I’ve been developing basic websites with php for a few years now but I need something to allow good site templating and eventually a CMS etc. I decided to use kohana as the basis for all of this but had a hard time finding any tutorials and the few I did fine were out of date ( < 3.0 .
Your tutorial has been great for me to understand the basics in practice (I understand the MVC concept but have never used it before so it was hard for me to know where to start).
There were a few issues I had as I'm using 3.3 but in the end I got it all working and can now look at developing my first application with kohana, thanks to this page! so thank you very much.
I think that is among the most important information for me.
And i am happy studying your article. However wanna
statement on some normal things, The web site style is great, the articles is really excellent :
D. Excellent process, cheers