In the last Kohana tutorial, we learn about URL rewriting and using mod_rewrite module to omit /index.php/ from the route addresses.
Until now, we have been using PHP variables to store page output, include HTML tags. That isn’t the most elegant way and certainly did not promote code seperation.
Using a view file not only seperates HTML scripts from PHP scripts it also create a seperation of concerns where controller will worry about logics while view will take care of page renderings only.
Understanding View
Views are file that contains the display information for your application. This not necessary means only HTML, but can be XML, Json or even Excel depends on your desired output format.
View files are of course still going to be PHP files unless template engine is used (such as Kostache). Developers will have the freedom to use conditional statements or iterations but up to themselves to restrict the temptation of applying logics in view files.
Create View
create new view files with controller name as folder and action name as file, respectively:
- \application\views\page\about.php
- \application\views\page\contact.php
about.php:
<!--?php defined('SYSPATH') or die('No direct script access.') ?--> <h1>About Us</h1> This is where you learn about this website.
and similarly, contact.php:
<!--?php defined('SYSPATH') or die('No direct script access.') ?--> <h1>Contact Us</h1> I will let you know how to find us in this page.
Rendering View
Update controller to render from view files instead:
class Controller_Page extends Controller { public function action_about() { //-- Render the view $view = View::factory('page/about'); $this->response->body($view); } public function action_contact() { //-- Render the view $view = View::factory('page/contact'); $this->response->body($view); } } // End Page
Summary
This is the day 4 of Kohana tutorial series, where we briefly discuss what is view and a basic example usage.
Pingback: Kohana Day 5: Variables in View | Travis, Travaganza