I am currently creating my own dependency injection software but am finding that it seems a lot like do this, do that to get this (if that makes sense).
class FactoryDatabase extends PDO
{
public function __construct(
$dsn,$user,$pass
) {
parent::__construct($dsn,$user,$pass);
}
}
class DependencyInjectionContainer
{
protected $Con;
public function __construct(
$db_factory
) {
$this->Con = $db_factory;
}
}
$container = new DependencyInjectionContainer(new FactoryDatabase(....
I am not fully understanding where to use constructors and where to use set/get methods since there is too many possibilities of achieving this.
For better practice, I'd like to understand if its better to use constructors or methods like these:
protected $Callbacks;
public function set(
$foo,$bar
) {
if(!empty($this->Callbacks[$foo])) {
$this->Callbacks[$foo] = $bar;
}
}
$container = new DependencyInjectionContainer();
$container->set('db', new FactoryDatabase(......
But now I get a problem where creating a get method will allow direct access to the database object rather than only through the DI container object.
I thought of a come around using both constructors and get/set methods:
public function __construct(
FactoryDatabase $db
) {
$this->Con = $db;
}
public function getFunction(
$foo
) {
return $this->Callbacks[$foo]($this);
}
public function getValue(
$foo
) {
return $this->Callbacks[$foo];
}
This allows me to use the Callbacks as values or anonymous functions but also access the methods inside the function, something like:
$container->set('db_select_members', function($obj){
return $obj->....
});
Is this best practice? Or how can I improve this DI software to allow full dynamics keeping Objects unclear to other Objects.
The only issue again is now there is direct access through the anonymous function to objects which could of just been accessed like:
$container->Object
So it seems a waste of time?