I’m implementing the observer pattern to all plugins to interact with my web app. Now, I want to make installing plugins painless (i.e just putting files into a plugin folder) like most web apps do.
For example:
A plugin with the name “Awesome Stuff” that executes code based on events that occur in the Auth class and the Content class would include the following files in the “/plugin” directory.
AwesomeStuffAuth.php
AwesomeStuffContent.php
I’ve got a solution that’s working, but I’m afraid it’s not efficient, as it has to cycle through ALL the declared classes before it actually finds what it’s looking for.
function __construct() {
//Get files in plugin directory that work on Auth
foreach (glob("plugins/*AuthPlugin.php") as $filename) {
//Include'em
include_once($filename);
}
//Get all declared classes
foreach (get_declared_classes() as $class){
if (substr($class,-10)=='AuthPlugin'){
$obj = new $class;
$this->addObserver($obj);
}
}
}
This is the __construct() method that I use with the Auth class, and other classes would have similar methods.
Is this an efficient way of doing this? Is it worth me connecting to a database to avoid cycling through all the declared classes? How about flat file?
Thanks so much for taking a look at this.
A possible solution would be to use __autoload to catch the moment where the plugin is requested and add it to a list of observers at this moment, based on naming conventions:
then in the Auth class:
Haven’t tested the code, but you should get the idea. It eliminates both the need to glob and the need to iterate over every declared class each time a class is created.