2

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

nfplee
  • 7,643
  • 12
  • 63
  • 124

2 Answers2

0

You don't have to inject into the constructor. A couple of ways to inject would be via a setter function

public function setUser(User $user) {
    $this->user = $user;
}

Or you can inject directly into the function that needs to interact with the class

public function someFunction(User $user) {
    $val = $user->doSomething();
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • Thanks but I don't really want do it this way either as otherwise I have to change my call to create the user instance. Ideally I'd like a static accessor but I'm not sure how to do it so that it shares the same instances (stored as an array) within my container. – nfplee May 09 '16 at 20:48
0

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);
Community
  • 1
  • 1
nfplee
  • 7,643
  • 12
  • 63
  • 124