On Monday 03 January 2011, Mike <[email protected]> wrote: > 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.
OK, that is a design problem...
>
> 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' );
>
> Results:
> 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?
Well, you can do this using abstract classes and interfaces. Also
you must try the autoloader:
http://php.net/manual/en/language.oop5.autoload.php
Probably this will help you a lot.
Best regards,
--
Daniel Molina Wegener <dmw [at] coder [dot] cl>
System Programmer & Web Developer
Phone: +56 (2) 979-0277 | Blog: http://coder.cl/
signature.asc
Description: This is a digitally signed message part.

