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.