I have created a very simple dependency injection container. I can create an instance of a class by saying:
$foo = $container->get(Foo::class);
This works well and allows me to inject dependencies in Foo's constructor. Now I wish to create an instance of a class by saying:
$user = new User();
I need to be able to access a service from the container within the User class but i'm not sure the best way to do it. Two ways I'd like to avoid is one passing the container into the constructor and secondly using the container's get method as shown above to create an instance of Foo.
I'd appreciate it if someone could show me the correct way to achieve this. Thanks
I've come up with a neat way of doing this. First I added a static property to my container which points to the current instance. For example:
class Container {
protected static $instance;
public function __construct() {
static::$instance = $this;
}
...
}
Then all I have to do is create a static get method e.g.:
public static function getInstance($name) {
return static::$instance->get($name);
}
Unfortunately it cannot have the same name. Click here for a hacky way of achieving it.
Now I can say the following in my User class:
var foo = Container::getInstance(Foo::class);