How to override module classes in Kohana 3?
In Kohana 3, how can I override / extend a module class?
eg. I want to add functionality to the Auth module specific to my application. In this case, I want to extend the abstract Auth class located in the class folder of the Auth module.
What naming convention should I use for my Auth class and where on the filesystem do I put my class file?
a source to share
To solve this problem, it is important to understand the hierarchical nature of the Kohana 3 structure. When it comes to overriding or extending modules, you need to do the following.
Let the Auth module be extended. When you look at the file system structure of the Auth module, you will notice that classes
there is a file in the directory named auth.php
. When you open this file, you will see the following:
<?php defined('SYSPATH') OR die('No direct access allowed.');
abstract class Auth extends Kohana_Auth { }
This defines an abstract class named Auth
that extends the class Kohana_Auth
. When you use any class references Auth
in your application, you mean this abstract class. The actual implementation is Auth
actually stored in the class Kohana_Auth
, which is in a folder Kohana
that is part of the module's directory structure.
To extend the module Auth
, i.e. to add your own functions, just place the file auth.php
in classes
your application directory folder. In your file, auth.php
you extend your version of the module Auth
by extending the class Kohana_Auth
. For instance:
<?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()
{
}
}
Due to the hierarchical nature of the framework, an abstract class Auth
defined as part of a module will never be loaded, because the framework loads your class Auth
first because it takes precedence. The extensible class Kohana_Auth
provides all the original functionality that you cannot implement and / or override.
For more information on controlling the behavior of this part of the documentation.
a source to share