Here is the 2nd part of 3 part series of Kohana tutorial. First part of this tutorial can be found here as Kohana Tutorial: For the beginners. Same as before it is going to be 10+/- steps.
- Template Controller in Kohana
- Kohana ORM (relation & validation)
Why Template Controller?
Its tedious and repetitive task to create and manage all the view files with header, footer, menu… etc all the time. So it could be better, if we had a common template to handle this kind of stuffs. Kohana have Template Controller to rescue you.
Lets create a template
We want that, our website will have common pattern with header, menu, css etc. We need to create a simple template file like as below.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Kohana Blog</title>
<!-- this is how, you you can add a css file -->
<?php echo HTML::style("public/css/template.css"); ?>
<!-- this is how, you you can add a javascript file -->
<?php echo HTML::script("public/js/jquery-1.6.4.js"); ?>
</head>
<body>
<div id="wrapper">
<!-- Header for the site -->
<div id="header"><h1>Kohana Blog</h1></div>
<!-- Menu for the site -->
<div id="navlist">
<ul>
<li><?php echo HTML::anchor("", "Home"); ?></li>
<li><?php echo HTML::anchor("article", "Articles"); ?></li>
<li><?php echo HTML::anchor("article/edit", "New Article"); ?></li>
</ul>
</div>
<!-- here we load all content -->
<div id="content">
<?php echo $content; ?>
</div>
<!-- no footer added -->
</div>
</body>
</html>
Working with template controller
Now we need to say our controller that, from now on you are going to handle the template yourself. To do this we need to change our article controller. We can do it in following way.
- Extend Controller_Article from Controller_Template instead of Controller
- Set the template for your controller as $template = “template”, since our template file is template.php in view folder.
- For all actions populate the $template as highlighted below at line 12. Do it for all other methods where required.
// extends the Controller_Template
class Controller_Article extends Controller_Template {
public $template = 'template';
...
public function action_index() {
$articles = ORM::factory('article')->find_all(); // loads all article object from table
$view = new View('article/index'); // load 'article/index.php' view file
$view->set("articles", $articles); // set "articles" object to view
$this->template->set('content', $view); // renders a view as a response
}
...
}
It should be fun and easy to do this. Now hit the url: http://localhost/kohana-blog/index.php/article and see the magic. We can see a nice look of our Kohana Blog.
Read more »