I'm trying to design a powerful plugin system that doesn't require any
(or extremely little) modification to my existing large code base. Hook
based systems unfortunately don't seem to meet this requirement. 

Is something like this possible in PHP?

//Magic function I made up, similar to __call(), 
//only it replaces "new $class" with its own return value.
function __instantiate( $class, $args ) {
    $plugin_class = $class.'Plugin';

    if ( file_exists( 'plugins/'.$plugin_class.'.php' ) {
        $obj = new $plugin_class($args);
        return $obj;
    } else {
        return new $class($args);

class MainClass {
    function doSomething( $args ) {
        echo "MainClass doSomething() called...\n";

class MainClassPlugin extends MainClass {
    function doSomething( $args ) {
        echo "MainClassPlugin doSomething() called...\n";

        //Modify arguments if necessary
        echo "MainClassPlugin modifying arguments...\n";

        $retval = parent::doSomething( $args );

        //Modify function output, or anything else required
        echo "MainClassPlugin post filter...\n";

        return $retval;

$main_class = new MainClass();
$main_class->doSomething( 'foo' );

MainClassPlugin doSomething() called...
MainClassPlugin modifying arguments...
MainClass doSomething() called...
MainClassPlugin post filter...

I realize PHP doesn't have this magical "__instantiate" function, but
does it have any similar mechanism that would work to automatically
load alternate classes, or have a class dynamically overload
itself during runtime?


PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to