Coding

Stupid(ly Useful) Kohana 3 Tricks – Safely Extending Base Classes


(Note: This post assumes a fairly high knowledge of how Kohana 3 works already. For a good tutorial, start here.)

Kohana 3 has a very neat structure that allows you to safely extend its base classes, adding functionality to classes as core as Kohana itself without ruining the interfaces other classes use to communicate with it.

The basic pattern is as follows:

abstract class Kohana extends Kohana_Core { }

class Kohana_Core {
    // Real functionality here
}

You may not recognize the brilliance inherent in this pattern if you don’t know a little something about Kohana – it autoloads classes in the following order:

# Application folder, then
# Module folders in the order defined in bootstrap.php, finally
# System folder

Which means, if you define your own Kohana class in your application/classes folder, then anytime anyone calls Kohana::debug(), they’ll be calling YOUR version of Kohana. Want to redefine debug() to output via FirePHP? Go nuts. Just make sure that your version of Kohana extends Kohana_Core.

But what if you’re developing a module, and you want people to be able extend ”your” version of Kohana? Well, you can follow the same pattern as the developers do:

abstract class Kohana extends Kohana_Modulename { }

abstract class Kohana_Modulename extends Kohana_Modulename_Core {}

class Kohana_Modulename_Core extends Kohana_Core {
    // Real functionality here
}

It looks a little convoluted, but bear with me. If people choose to define Kohana directly, they can, thus cutting off your module entirely. But if people choose to extend from your module, they can define Kohana_Modulename and place their functionality in there, remembering to extend Kohana_Modulename_Core from that class, and the whole chain remains. In fact, they can extend the chain further with this same pattern for their own Modulename.

Now, this doesn’t really help when two modules BOTH want to redefine Kohana and aren’t aware of each other, but that is probably always going to be a problem.

Coding
Code faster with simple Sublime Text improvements
Coding
Rage-quit support for fish shell
Coding
Gulp.js – an AMAZING build system!
  • Dan Chadwick

    Dan ChadwickDan Chadwick

    Author

    Thanks, for this, I ended up using this technique in order to retroactively add modules (eg from a db) in the bootstrap to the Kohana::$_modules variable with an “add_modules” function.

    Very helpful. Thanks


  • Acky

    AckyAcky

    Author

    Thanks for your post-reminder ;)
    I was extending core classes in Kohana 2. And now, some time ago, working with the third version I stuck a little. But extending looks like as in the previous version.