What's the best way to manage a singleton?

I've been messing around with various PHP frameworks. I am currently trying PEAR :: Log. I decided that I would use his function singleton

to make sure there is only one instance of the class around.

I have a small daemon-like script, I wanted to add logging because it was probably the simplest script on the system under test. This script has several features. I probably want to register things inside functions.

I have a question, what is the best way to manage this single?

I call it:

&Log::singleton($handler, $name, $ident, $conf, $maxLevel);

      

in every function doesn't seem perfect, especially since I've already specified all the parameters in the initial call. Pear :: Log serializes this information, but from what it looks like, you still need to provide all of these variables to get an instance.

Another alternative is to pass an instance to each function. Again, it seems like it is less than perfect.

I suppose you could make the instance "global".

What are you in this situation? Are there any better solutions?

+1


source to share


4 answers


I don't know much about PEAR :: Log, but why not create another singleton that wraps / simplifies logging.

class Logger {

    private static $log;

    private function __construct() { }

    public static function init(Log $log) {
        self::$log = $log;
    }

    public static function get() {
        return self::$log;
    }

}

      



Once initialized Logger

with an instance, Log

you can access it via Logger::get

. Since dereferencing exists in PHP, you can do

Logger::get()->doSomething($foo, $bar);

      

+1


source


It's even better if your ultimate goal is to just blindly call

Logger::Write("Something happened");

      

wherever you need it, you can take Michal's solution one step further with



class Logger {
    private static $log = null;

    public static function init(Log $log) {
        self::$log = $log;
    }

    public static function Write(String $str) {
        if($log == null)
            init(Log::singleton(...));

        $this->log->Write($str);
    }
}

      

This way your log will be initialized once, the first time it is used.

+3


source


Just use a global instance. You should have a file somewhere that all other files should include. Just create it there. If you have anything against globals, you probably shouldn't be programming in PHP.

+1


source


Another alternative is to pass an instance to each function. Again, it seems like it is less than perfect.

Basically you have the choice of passing dependencies for each function, for each object instance, or in one of the global scopes. I find that using object instance scope usually strikes a good balance of flexibility. As a general rule, you should try to limit the scope of variables as much as possible, so if that makes sense be sure to go through the function parameters.

0


source







All Articles