I have some code like so:
class MyClass
{
public function maybeDoSomething(maybe)
{
if (maybe) {
$this->_doSomething();
}
}
protected function _doSomething()
{
$something = Something::getInstance();
$something->do();
}
}
There are a couple of problems here I’d like to fix - the hard-coded dependency and the use of a singleton class.
One solution would be to use a dependency injection container, which would solve both problems (The Something class could be changed to a standard class and the container would ensure only a single instance is created).
class MyClass
{
public function __construct(ISomething $something)
{
$this->_something = $something;
}
public function maybeDoSomething(maybe)
{
if (maybe) {
$this->_doSomething();
}
}
protected function _doSomething()
{
$this->_something->do();
}
}
However, I don’t know how you could do that without the container creating an instance of Something, even though it may not be needed. I’d like to avoid instantiating objects that aren’t used.
Another option would be a dependency suction container (for want of a better term) that is passed into MyClass. Then when _doSomething() is called, it gets the dependency from the container.
class MyClass
{
public function __construct(Container $container)
{
$this->_registry = $container;
}
public function maybeDoSomething(maybe)
{
if (maybe) {
$this->_doSomething();
}
}
protected function _doSomething()
{
$this->_registry->get('ISomething')->do();
}
}
That ensures that the Something class would only be instantiated when needed, but adds another dependency to the class and seems rather messy.
Anyone have a better idea?