S
S
Sergey2012-06-18 13:17:36
PHP
Sergey, 2012-06-18 13:17:36

How to configure Singleton initialization?

There is a library in which there is a class that allows the existence of only one instance within one process, i.e. in fact it is a Singleton. The trouble is that the initialization of this very instance has several dynamic parameters that must be passed somehow.
The solution should work on PHP > 5.2. The only thing that came to my mind:

public static function init($params) {
    if(self::$instance) {
      throw new Exception(__CLASS__ . ' already initialized');
    }
    $class = __CLASS__;
    self::$instance = new $class($params);
  }

  public static function getInstance() {
    if(!self::$instance) {
      throw new Exception(__CLASS__ . ' is not initialized');
    }
    return self::$instance;
  }

But it doesn't seem to be the best. Does anyone have any other ideas, please?
Thank you!

Answer the question

In order to leave comments, you need to log in

8 answer(s)
L
LastDragon, 2012-06-18
@LastDragon

Do not bind to a singleton (the fact that there is actually only one instance does not make the class a singleton, especially considering that its behavior depends on the parameters of the constructor). In my opinion, it would be most logical not to use singleton, but to store the only instance of this class in the registry (the creation of an instance will be somewhere in the code, depending on the architecture of your application).

G
Gron, 2012-06-19
@Gron

en.wikipedia.org/wiki/Multiton_pattern
en.wikipedia.org/wiki/Immutable_object
Of course I'm sorry, but if you need exactly singletons - use Multition (aka a pool of singletons), if you want the state of the object that you created 1 time to change - use immutable (Immutable )

S
Sergey, 2012-06-18
@liaren

Copy of this question on StackOverflow: stackoverflow.com/questions/11081324/singleton-initialization-configuration

G
gaelpa, 2012-06-18
@gaelpa

If the class is a singleton, then its parameters are global within the application or session.
1. Maybe let him find out his configuration from an external source?
2. Make a wrapper method / class that collects (itself) parameters and passes them to the non-singleton constructor, after which it returns the same instance. The wrapper is at the application level, so encapsulation doesn't suffer.

N
Nikolai Vasilchuk, 2012-06-18
@Anonym

Here is an example of a singleton in PHP

    public static function singleton()
    {
        if (!isset(self::$instance)) {
            echo 'Создание нового экземпляра.';
            $className = __CLASS__;
            self::$instance = new $className;
        }
        return self::$instance;
    }

It seems obvious to me to do something like this
    public static function singleton($params)

Actually, it will turn out approximately what you described.
It seems to me that this is normal.

C
CrazySquirrel, 2012-06-18
@CrazySquirrel

<?
class MySingleton
{

        static private $_instance;

        private function __construct($params)
        {
                //При необходимости, недостающие параметры обработать тут.
                $this->_params = $params;
        }

        public static function getInstance()
        {
                if (!self::$_instance instanceof self) {
                        self::$_instance = new self(func_get_args());
                }

                return self::$_instance;
        }

        ...

}


MySingleton::getInstance('param1', 'param2', 'paramN')->doSomething();


And it's not kosher at all.
Use Registry.

A
Anatoly, 2012-06-18
@taliban

Separate constructor and parameters:

class Singleton{
    static public punction getInstance(){ ... }
    public function applyParams($params){ ... }
}

$singleton = Singleton::getInstance()->applyParams($param1);
// some code
// change param
$singleton->applyParams($param2);

A
AxisPod, 2012-06-19
@AxisPod

I would use a static method for initialization. And which would throw an exception if the instance has already been created.
singleton::init(.....);
Singleton::getInstance()…
Singleton::init(....); // throw exception...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question