Kohana Framework 3 Tutorial part 2 – quick introduction to controllers and the framework
Kohana Framework 3 Tutorial part 2 – quick introduction to controllers and the framework
Before building the actual Twitter application I think it would be useful to go over the way the framework works by default. So right now we have a clean and working install. Let’s see how it works.
<?php defined('SYSPATH') or die('No direct script access.'); class Controller_Messages extends Controller { public function action_show($id = NULL) { if($id == NULL) echo "no argument given"; else echo "show message with id: $id"; } } // End Messages
The first line
<?php defined('SYSPATH') or die('No direct script access.');
is simply there to avoid direct access to this file (this should never happen, but it is an extra security measure). Make sure you put this at the top of all your files.
Next we define the class:
class Controller_Messages extends Controller {
This if the Kohana Naming convention (actually it also has something to do with where you place your files, but we will get to that a bit further down the road). Here we have created a class “Controller_Messages” that extends “Controller” (part of the Kohana core). Next we define out method (“messages/show/”):
public function action_show($id = NULL) { if($id == NULL) echo "no argument given"; else echo "show message with id: $id"; }
The method takes an argument (“messages/show/9548″) or makes it NULL if none is passed (“messages/show/”). The rest of the code is pretty self explanatory. Now try going to “http://localhost/messages/show/” and then “http://localhost/messages/show/439834“. Hopefully everything will work as expected. Here you have seen the most basic way of creating a controller and a corresponding request method.
One last thing. What if you go to “http://localhost/messages/showall“? Well it will throw a “method not found” exception and that makes sense. But what about “http://localhost/messages/“? That will also throw the above exception, but how should we name this method? Well this depends on the framework convention again: in kohana if no is given in the URI the default method “action_index” will be called. We have not defined this yet. So let’s quickly do that. Here is the final code for the messages controller:
<?php defined('SYSPATH') or die('No direct script access.'); class Controller_Messages extends Controller { public function action_index() { echo "no <action> given"; } public function action_show($id = NULL) { if($id == NULL) echo "no argument given"; else echo "show message with id: $id"; } } // End Messages
Try it out and see if it works. Hopefully it does . This is meant to be a short introduction to the basic use of controllers in MVC frameworks, which you will need to be able to follow the next parts of this tutorial series.
- Printer-friendly version
- Log in to post comments
- 3269 reads