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.

 

Changelog: Upgrade Kohana 3.1.3 to 3.1.3.1

Appearently Koahan made a silence release on 6th of May for some emergency bug fixes.

Kohana 3.1.3.1 was released in 4 days to cover 2 major bug fixes.

 

In a Nutshell

  • Kohana uncompressed folder size has decreased (somehow) by 10 Kb to 1.94 Mb
  • 5 files modified.

 

The Full Length

This will cover only the logical changes. Texture and style changes will be overlooked. Minor code refactoring may also be ignored if the changes are for standardisation.

/system

  • /classes/kohana/request/client/external.php
    • Parse query parameter in _http_execute() function.
  • /classes/kohana/request.php
    • Bug fix redudant query parameters in uri.
  • /classes/kohana/session.php
    • Remove error logging upon exception case when reading a session.

 

Summary

This is a technical blog post covering implementation changes of latest Kohana MVC framework, version 3.1.3.1 from its previous version 3.1.3. I will line out code changes to help enthausiast PHP developer understanding the techniques and security concerns.

Changelog: Upgrade Kohana 3.1.2 to 3.1.3

This is my first changelog  Kohana MVC framework I cover on. I follow closely on developments of Kohana as it is the PHP MVC of my choice and I am yet to learn from its design.

Kohana 3.1.3 is a maintenance release since last revision more than 2 months ago resolving 18 non-critical bug fixes.

 

In a Nutshell

  • Kohana uncompressed folder size has increased by 20 Kb to 1.95 Mb
  • 2 files added, 30 files modified and 5 files renamed.

 

The Full Length

This will cover only the logical changes. Texture and style changes will be overlooked. Minor code refactoring may also be ignored if the changes are for standardisation.

/module

  • /database/classes/kohana/database.php
    • add concrete implementation on Kohana_Database.disconnect() function.
  • /database/classes/kohana/database/exception.php
    • remove all functions within Kohana_Database_Exception class (extends from Kohana_Exception) leaving it empty.
  • /database/classes/kohana/database/mysql.php, /database/classes/kohana/database/pdo.php
    • clear parent instance upon Kohana_Database_MySQL.disconnect() function (extends from Database class).
  • /unittest/classes/kohana/unittest/helpers.php
    • tweak regular expression in Kohana_Unittest_Helpers.set_environment() function.

/system

  • /classes/kohana/http/header.php
    • Add one more default value ‘last-modified’ in last parameter of Kohana_HTTP_Header.parse_header_values() function.
  • /classes/kohana/kohana/exception.php
    • Save a copy of unmodified integer code upon construction of a Kohana_Kohana_Exception instance.
    • Force exit upon error catchings in Kohana_Kohana_Exception.handler() function.
  • /classes/kohana/request.php
    • Cleanse query parameters from URI upon construction of a Kohana_Request instance.
    • Conditional query parameters upon returning value of URI in Kohana_Request.uri() and Kohana_Request.url() functions.
    • Deprecating Kohana_Request.send_headers() function.
  • /classes/kohana/request/client/external.php
    • Resolve POST fields in Kohana_Request_Client.execute() function.
  • /tests/kohana/ExceptionTest.php, /tests/kohana/RequestTest.php, /tests/kohana/ValidTest.php
    • Add and update test cases.


Summary

This is a technical blog post covering implementation changes of latest Kohana MVC framework, version 3.1.3 from its previous version 3.1.2. I will line out code changes to help enthausiast PHP developer understanding the techniques and security concerns.

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.