views:

395

answers:

1

In Kohana 3, how can I override/extend a module class?

E.g. I want to add functionality to the Auth module that is specific to my application. In this case I want to extend the abstract Auth class located in the classes folder of the Auth module.

What naming convention should I use for my Auth class and where in the file system do I place my class file?

+2  A: 

To solve this issue it's important to understand the hierarchical nature of the Kohana 3 framework. When it comes to overriding or extending modules you need to do the following.

Let's extend the Auth module. When you look at the Auth module file system structure you notice that in the classes directory there is a file called auth.php. When you open this file you see the following:

<?php defined('SYSPATH') OR die('No direct access allowed.');

abstract class Auth extends Kohana_Auth { }

Here an abstract class named Auth defined which is extending the Kohana_Auth class. When you use any references to the Auth class in your application you're referring to this abstract class. The actual implementation is of course kept in the Kohana_Auth class which is located in the kohana folder and part of the module file structure.

To extend the Auth module, to add your own functionality e.g., you simply place an auth.php file in the classes folder of your application. In this file you extend your version of the Auth module by extending the Kohana_Auth class. Like so:

<?php defined('SYSPATH') OR die('No direct access allowed.');

class Auth extends Kohana_Auth {

   public function get_user()
   {
      $result = parent::get_user()

      // implement your functionality here.

      return $result;
   }

   public function my_added_functionality()
   {
   }

}

Because of the hierarchical nature of the framework, the abstract class Auth defined as part of the module will never be loaded because the framework loads your Auth class first. The class you extend, Kohana_Auth, provides all the auth functionality.

For more information on the behavior checkout this part of the documentation.

Luke