开发者

redeclare variable, or effectivly reload class at runtime in php

I need to be able to "effectivly" redeclare my class, so that during runtime, whilst my PHP IRC bot is running I can reload modules as the code base changes, which requires getting the class, but PHP won't allow it to be redeclared, nor is there a way to undeclare a class.

Is there a way I can acheive this? Perhaps some other method? I've tried "runkit", but that failed.

My current code is here: http://pastie.org/private/ptj7c0t0teh3nnzn7ehcg

So to clarify, I effecivly need to 开发者_开发百科be able to reload my class, instatiate it and put into a property in my main bot class once code has changed in said module, whilst the bot is running (run-time).


A brief look at your application leads me to believe your best course of action is to use a base class as suggested in the comment above.

Something to the extent of:

class IRCModule {

    private static $module_dir = ''; //put your module directory here w/o trailing slash

    public static function getModule( $module ) {

        //if the module directory doesn't exist, don't do anything
        if( !is_dir( self::$module_dir.DIRECTORY_SEPARATOR.$module ) ) return false;

        //load the module file
        $fname = scandir(self::$module_dir.DIRECTORY_SEPARATOR.$module);
        $fname = $fname[2]; //first 2 elements will be . and ..

        require_once( self::$module_dir.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$fname );

        $className = str_replace('.class.php',NULL,$fname);

        return new $className();

    }

}

You would then extend that using your modules. That would allow you to overwrite a module by simply removing it's old file /my/module/dir/moduleName/moduleNameV1.0.class.php and replacing it with a new version /my/module/dir/moduleName/moduleNameV1.1.class.php

As mentioned in the comments, this will eventually fill the memory on the server, so you should schedule a reboot of the service each time you make substantial changes, but it also allows you to load new versions on demand without stopping the service.

A more stable approach would be to take advantage of process control and spin off daemons for each connection from your parent script, or implement a cache system that stores all data on the disk/database so that you can detect a change in module version and instantly reboot the server. But the solution above should work for you for the time being :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜