I'm currently using Laravel and have a pretty good general grasp now on how the dependency injection and service container works now. I see it working very well when programming to interfaces, but what about concrete classes?
I utilize a service layer between my controllers and models. The point of the service objects was so that I could easily reuse their methods elsewhere, like in a different controller. But there are cases where I also need to use a service inside another service.
So I've been using the constructor for the dependency injection inside my services. The issue I kind of see is that sometimes I only need a service (inside one of my other services) for 1 method. So doing it in the constructor makes it rather large. On the other hand, since I've been setting these parameters in the constructor, I can't simply new-up an instance on demand, since it requires those parameters. For example, let's say I have an OrderService
class, and for the constructor, I see two ways I can go about it:
public function __construct(FileUploadService $fileUploadService)
{
$this->fileUploadService = $fileUploadService;
}
or
public function __construct()
{
$this->fileUploadService = new FileUploadService;
}
I've mostly been doing it the first way, but have been thinking about the second. If I ever needed this OrderService
somewhere else in the app, I can't simply create a new instance since it relies on the FileUploadService
, unless I create a new instance of that too. But you can see that it will start to cascade without the dependency injection, because what if the FileUploadService
depends on something also? It's just easier to resolve it out of the container.
Maybe there's something I'm missing, because it almost feels like a catch 22 in some ways. I'd like to note that a majority of these classes I'm injecting are concrete classes, so I don't need to swap them out at any particular point.
I've thought about just creating a new instance in the constructors for each service I need, that way I can also new-up the instance without providing parameters. But I like to follow best practices, so I was wondering what other experienced developers thought about this.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire