简体   繁体   中英

Laravel dependency injection on entity object

Im trying to get the following working: Im using the laravel framework and the service provider to inject dependencies. I created a Session object and a Session interface, the session object implements the session interface. I did this because i dont want to couple the session to a specific framework implementation (in this case laravel).

I also have a entity object X, this object needs the session for getting some data out of it. In the constructor it has the ISession, this would mean it would be injected by the IOC. But i also need to create these entity objects with the new operator. This would mean that i need to pass the implementation of the session. How can i avoid this ? I could use App::make(), but this would mean that i have laravel coupled to my entity object.

The purpose of the binding on the IoC container is to avoid using the new operator everytime you need to create a new instance

So, you have to make the binding between the interface and the implementation you want, and then use:

$session = App::make('ISession');

to get the implementation you have binded to the interface.

Yes, you'll have your Laravel container coupled to your application, but Laravel IS your application

On Laravel all my interfaces are resolved through a Service Provider, where I bind the Session interface to a certain implementation.

Like:

$this->app->bind('session-interface-namespace', function(){return SessionImplementation()})

Once I do it, all the classes requiring the Session interface will resolve my Session implementation as their "real" dependency. With that, my business/domain logic it's separated from my, let's call it like that, infrastructure logic.

The next step I would do is an entity factory.

Hope it helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM