Thursday, March 24, 2016

Creating a Kohana Module


Creating a Kohana module is simple. In this post we shall create a very basic Kohana 3 module, activate it and use it.


Let's say the name of our module is "Olive". 


1. Create a folder named 'olive' in the modules folder.

2. Create a folder named 'classes' in 'olive' folder.
3. Create a file named olive.php in the classes folder.

Type the following code in 'olive.php' file:

<?php defined('SYSPATH') or die('No direct script access.');

 class Olive {
   function index()
        {
              echo "Hello from Olive Module";
        }

   static function pickle()
        {
        return "We have been making and serving Olive Pickles for the world since 1867";

        }
   static function oil()
        {
        return "We have been making and serving Olive Oil for the world since 1867";   
        }
}
?>

Kohana will look for olive.php file in modules/olive/classes folder. 

Enable the Olive module in bootsrap.php file:




Now let's use the module in a controller. Create a file named OliveTest.php in application/classes/controller folder and type the following code in that file:

<?php defined('SYSPATH') or die('No direct script access.');
class Controller_OliveTest extends Controller_Template {

public function action_index()
{
echo "<h1>Welcome to Olive Module</h1>";
}

public function action_oil()
{
echo Olive::oil();
}

}

Point your browser to this url: http://localhost/project/olivetest/

You should see: 

Welcome to Olive Module

Point your browser to this url: http://localhost/project/olivetest/oil


You should see: 
We have been making and serving Olive Oil for the world since 1867


Further Experiment
------------------------
Now create a folder named 'controller' in the classes folder and copy the olive.php file in the controller folder. Add 'Controller_' before 'olive; in the class declaration file so that it looks like this: class Controller_Olive { 

Point to url: http://localhost/project/olivetest/oil

You should get a Fatal error: 

ErrorException [ Fatal Error ]: Class 'Olive' not found

That is because name of the class is now Controller_Olive. But, in the controller file named test.php, you are calling the controller as 'Olive'. We need to correct this. Go to test.php and edit the action_oil function like so:

public function action_oil()
{
echo Controller_Olive::oil();
}

Point to url: http://localhost/project/olivetest/oil. Everything should be okay. 

No comments:

Post a Comment