How to override module classes in Kohana 3?
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 A开发者_Python百科uth class and where in the file system do I place my class file?
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
is 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 of Auth
is actually kept in the Kohana_Auth
class which is located in the Kohana
folder which part of the module directory structure.
To extend the Auth
module, i.e. add your own functionality, you simply place an auth.php
file in the classes
folder of your application directory. In your auth.php
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 because it takes precedence. The class you extend, Kohana_Auth
, provides all the auth original functionality you can no extent and/or override.
For more information on the behavior checkout this part of the documentation.
精彩评论