I didn't find out how to format spoilers, so it'll be kinda long(
Let's say, I need to use object method that requires some service within dependency injection container. For example, logger service. And let's say that this object is created inside method of another class that may or may not require DIC. Let's also assume that it may be nested deeper than 2 levels.
How should I inform that bottom-level class about DIC presense?
Should I pass it through all classes, possibly adding DIC knowledge to objects that don't need it?
Something like:
index.php:
use Phalcon\Di\FactoryDefault\Cli;
use Phalcon\Logger\Adapter\File;
$di = new Cli();
$di->setShared('logger', function () {
return new File('app.log');
});
$di->set('creator', 'CreatorClass');
$oCreator = $di->get('creator');
$oCreator->doSomeStuff();
CreatorClass.php:
use Phalcon\Di\InjectionAwareInterface;
class CreatorClass implements InjectionAwareInterface
{
protected $_di;
public function setDI(\Phalcon\DiInterface $dependencyInjector)
{
$this->_di = $dependencyInjector;
}
public function getDI()
{
return $this->_di;
}
public function doSomeStuff()
{
$this->_di->set('utilizer', 'UtilizerClass');
$oUtilizer = $this->_di->get('utilizer');
$oUtilizer->useProvider();
}
}
UtilizerClass.php:
use Phalcon\Di\InjectionAwareInterface;
class UtilizerClass implements InjectionAwareInterface
{
protected $_di;
public function setDI(\Phalcon\DiInterface $dependencyInjector)
{
$this->_di = $dependencyInjector;
}
public function getDI()
{
return $this->_di;
}
public function useProvider()
{
$this->_di->set('provider', 'ProviderClass');
$oProvider = $this->_di->get('provider');
echo $oProvider->getData();
echo $oProvider->getData();
}
}
ProviderClass.php:
use Phalcon\Di\InjectionAwareInterface;
class ProviderClass implements InjectionAwareInterface
{
protected $_di;
public function setDI(\Phalcon\DiInterface $dependencyInjector)
{
$this->_di = $dependencyInjector;
}
public function getDI()
{
return $this->_di;
}
public function getData()
{
$data = 'data';
$oLogger = $this->_di->get('logger');
$oLogger->info($data . ' retrieved');
return $data;
}
}
Or, should i use DI statically only where it really need to be used?
Something like: index.php:
use Phalcon\Di\FactoryDefault\Cli;
use Phalcon\Logger\Adapter\File;
$di = new Cli();
$di->setShared('logger', function () {
return new File('app.log');
});
$oCreator = new CreatorClass();
$oCreator->doSomeStuff();
CreatorClass.php:
class CreatorClass
{
public function doSomeStuff()
{
$oUtilizer = new UtilizerClass();
$oUtilizer->useProvider();
}
}
UtilizerClass.php:
class UtilizerClass
{
public function useProvider()
{
$oProvider = new ProviderClass();
echo $oProvider->getData();
}
}
ProviderClass.php:
use Phalcon\Di;
class ProviderClass
{
public function getData()
{
$data = 'data';
$oLogger = Di::getDefault()->get('logger');
$oLogger->info($data . ' retrieved');
return $data;
}
}