Kohana Day 5: Variables in View

In the last Kohana tutorial, we learn about 2nd part of MVC: views. This tutorial we will discuss further (but not quite in depth) on view.

To display dynamics in your webpages through views, you should have the values been prepared by controller and passed forward to view in its display form. In view, you should be prohibited to perform logical operations and avoid formatting operations. For example, to display age of an user, do not query database for his Date of Birth in view, avoid passing date to then be formatted in view, instead you should have the display format prepared by controller and pass that view that can be simply printed out from it. This is the fundamental to separation of concerns.

There are 2 methods to assign variables to a view: through set() method and bind() method. The difference is set() is passing by value whereas bind() is passing by reference. This means bind() has the following feature:

  • Passing by reference means not as memory exhaustion when dealing with complex objects
  • You may modify the object after it has been binded to a view.

 

Update page controller

open up \application\classes\controller\page.php and apply usage of variable setting and bindings:

class Controller_Page extends Controller {
 
	public function action_about()
	{
        //-- Arrange
        $page_title = "About Us - Kohana Demo Site";
        $page_header = "All About Us";
        $message = "This is where you learn about this website.";
 
        //-- Render the view
        $view = View::factory('page/about');
        $view->set("title", $page_title);
        $view->set("header", $page_header);
        $view->set("message", $message);
        $this->response->body($view);
	}
 
	public function action_contact()
	{
        //-- Arrange
        $page_title = "Contact Us - Kohana Demo Site";
        $page_header = "Contact Information";
        $message = "I will let you know how to find us in this page.";
 
        //-- Set Contact Details to an Anonymous Object
        $contact_info = new StdClass;
        $contact_info->telephone = "1800 111 888";
        $contact_info->address = "123 Fake st. Springfield";
        $contact_info->email = "demo@demosite.com";
 
        //-- Render the view
        $view = View::factory('page/contact');
        $view->set("title", $page_title);
        $view->set("header", $page_header);
        $view->set("message", $message);
        $view->bind("contact_info", $contact_info);
        $this->response->body($view);
	}
 
} // End Page

 

Update views

Now updates their views respectively.

\application\views\page\about.php

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title><?php echo $title; ?></title> 
    </head>
    <body>
        <h1><?php echo $header; ?></h1>
        <p><?php echo $message; ?></p>
    </body>
</html>

\application\views\page\contact.php

 

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title><?php echo $title; ?></title> 
    </head>
    <body>
        <h1><?php echo $header; ?></h1>
        <p><?php echo $message; ?></p>
        <ul>
            <li>Telephone: <?php echo $contact_info->telephone; ?></li>
            <li>Address: <?php echo $contact_info->address; ?></li>
            <li>Email: <?php echo $contact_info->email; ?></li>
        </ul>
    </body>
</html>

 

In addition

There is a third method to assign variables to a view which you should avoid. That is global setting/binding by set_global() and bind_global() methods. The concept of global variables in programming language, it is a variable that can be accessed through all scopes in a design. This has been fraud upon has it promotes laziness oppose to appropriately layer your design.

 

Download

 

Summary

This is the day 5 of Kohana tutorial series, where we covers usage of variables in view.

 

Kohana Day 4: Basics with View

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-&gt;response-&gt;body($view);
	}
 
	public function action_contact()
	{
        //-- Render the view
        $view = View::factory('page/contact');
        $this-&gt;response-&gt;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.

Kohana Day 3: URL Rewriting

In the last Kohana tutorial, we start off with understanding of controller and action usage, and then went on with very basic usage.

One if your first webpage is http://localhost/kohana/index.php/page/about. The existence of /index.php/ may be bit of an eye sore and many desires for clean URLs, which is one of the given advantage by using an MVC framework.

Understanding URL Rewrite/Redirect

URL rewriting or redirecting is an ability on your web server (through extension) to navigate its webpages through certain web addresses.

For our example: we want to say http://mysite.com/page/contact to get to http://mysite.com/index.php/page/contact.

By using URL rewriting, you may gain the following:

  • Clean and friendly URL increase readability and SEO
  • Increase security by hiding actual file structure and limited accessible folders/files

mod_rewrite Module

mod_rewrite is a module included with Apache web server since version 1.3. This uses rule-based rewriting engine that able to rewrite your request URLs on the fly. It is designed to support large set of rules whether it’s regular expression, conditional or determined by server variables.

For further reading on mod_rewrite module:

You can find it as “rewrite_module” in WampServer. It is not enabled by default, always check its availability before attempt to debug the rewrite rules.

Checking mod_rewrite enabled in WampServer

 

Setting URL rewrite in Kohana

rename .htaccess

.htaccess file is where you define your rewrite rules. Kohana framework has provided an example.htaccess as template.

Rename the filename to .htaccess. You will have problem doing this in Windows has it doesn’t allow you to create file without filenames (since “htaccess” are treated as filetype by Windows). You can walk around this easily by going through DOS prompt using “ren” command.

Windows won't allow to rename/create files without a name

Renamed through DOS prompt

Update .htaccess file

Kohana has prepared an almost ready to go rules for you. You will however, need to set your RewriteBase if you are not working from root of virtual directory. In this tutorial, you are working off “kohana” folder, so it should be “RewriteBase /kohana/” and your .htaccess file should looks like:

# Turn on URL rewriting
RewriteEngine On
 
# Installation directory
RewriteBase /kohana/
 
# Protect application and system files from being viewed
RewriteRule ^(application|modules|system) - [F,L]
 
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
 
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT,L]

Update bootstrap

Next is to update your bootstripe file in \application\bootstrap.php to omit index.php file by modify your Kohana initialisation setting:

/**
 * Initialize Kohana, setting the default options.
 *
 * The following options are available:
 *
 * - string   base_url    path, and optionally domain, of your application   NULL
 * - string   index_file  name of your index file, usually "index.php"       index.php
 * - string   charset     internal character set used for input and output   utf-8
 * - string   cache_dir   set the internal cache directory                   APPPATH/cache
 * - boolean  errors      enable or disable error handling                   TRUE
 * - boolean  profile     enable or disable internal profiling               TRUE
 * - boolean  caching     enable or disable internal caching                 FALSE
 */
Kohana::init(array(
	'base_url'   => '/kohana',
    'index_file' => FALSE
));

Now try to access with following URLs again:

  • http://localhost/kohana/page/about
  • http://localhost/kohana/index.php/page/about
  • http://localhost/kohana/page/contact
  • http://localhost/kohana/index.php/page/contact

You now have URL rewriting working where you can access to your web pages with index.php and without!

All examples after this tutorial will not have /index.php/ in the sample URLs. You may continue working on tutorials as normal without URL rewritings, just remember to add /index.php/ before your routines.

 

Summary

This is the day 3 of Kohana tutorial series, covering the URL rewriting and basics on mod_rewrite module.

Kohana Day 2: Basics with Controller and Action

In the last Kohana tutorial, we got ourselves started working with a MVC framework by bootstrapping Kohana 3.1.2 and have our very first hello world page.

Understand Controllers

Controller is the center platform to a developer as this is where you apply logics to your requests. Controller stands between models and the views, passing change requests to model and rendering criteria to view.

A controller can have several actions. They are public methods available to users through web requests. Controller/Action pairs are often represented through friendly URL format: http://{website}/{controller}/{action}/{parameter1}/{parameter2}/… (or without URL rewriting, it is http://{website}/index.php/{controller}/{action}/{parameter1}/{parameter2}/…)

For example:

  • http://mysite.com/Page/About
    • loads “Page” controller and its “About” action
  • http://myshop.com/Car/Detail/123
    • loads “Car” controller and its “Detail” action passing “123″ as first parameter.

You can of course, customise your URL routine breaking away from conventional format. We will cover this later in the tutorial.

Create Page Controller

Let us start by creating a new controller “Page” that will holds all static pages in your web application: \application\classes\controller\page.php

class Controller_Page extends Controller {
 
	public function action_about()
	{
        $msg = '<h1>About Us</h1><p>This is where you learn about this website.</p>';
		$this->response->body($msg);
	}
 
	public function action_contact()
	{
        $msg = '<h1>Contact Us</h1><p>I will let you know how to find us in this page.</p>';
		$this->response->body($msg);
	}
 
} // End Page

Notice Kohana requires Controller_ prefix when creating controller classes andaction_ prefix when creating methods as public actions. Any methods defined within a controller but without action_ prefix will be considered as private method and will not be accessible through web requests.

Now try to access with following URLs:

  • http://localhost/kohana/page/about
  • http://localhost/kohana/index.php/page/about
  • http://localhost/kohana/page/contact
  • http://localhost/kohana/index.php/page/contact

Since we haven’t setup URL rewriting, all routines have to go through index.php page, which will be covered in the next tutorial.

Going Advance

$this->request

Every controller will have access to the Request object that gives you information about current request. More details on Kohana 3.1 User Guide.

before() and after()

You can use before() and after() functions to collect common logics you required to perform in all actions of a controller (such as logging, authentication, preload… etc). More details on Kohana 3.1 User Guide.

 

Summary

This is the day 2 of Kohana tutorial series, covering the very basics of controller, which is the bread of a MVC application.

Kohana Day 0: Ready to Go

This will be a starting point of a new tutorial series on Kohana MVC frameworks. I will do a walk through on varies sections and will divided to several parts rather than rush through the entire framework in one go. The example code will be incremental continuous building a web project for as long as I can handle. I will also make it possible to join the tutorial from the middle, that way if you only need to learn a particular section, you won’t feel lost without gone through the previous build ups.

Assume Knowledge

Basic PHP and MySQL skills are pre-requisite. It is also good idea to have basic ideas of what MVC is and does.

Coding Style

I will follow strict Kohana coding conventions to stay in consistent as well as promoting best practices.

Configuration

Walk through will be running in Windows XP SP 3 with WampServer 2.1a:

  • Apache 2.2.17
  • MySQL 5.5.8
  • PHP 5.3.3

Code base will be base on the latest stable version of kohana to date starting with Kohana 3.1.2 and will stay up to date, which I will mentioning upgrade during tutorials.

Topic List

I will be running through the chronicle order as per KO3′s user guide:

  • Installation and Hello World
  • Basics on Controller and View
  • Basics on Model
  • Page Template and Theming
  • etc

This is only a draft topic list and may rearrange or add more topics if I found it’s reasonable to.

 

Stay tune on this post as I will add the tutorial links as we go!