1
votes

I got a huge Symfony project. I created many service and subservices to epurate the Controller and Services code.

In my code i instantiate these services with:

$this->get('MyServiceName')->myMethod($foo);

One of my coworker use the new keyword to instantiate the class:

    $myservice = new Service();

    $refid = $myservice->mymethod($foo);

So i wondering, is it a best practice? Should i rewrite that codeĀ ? What are the impact of this kind of code on the maintenability and the performance of the application?

2
in services you can pass dependencies (like doctrine,service container,router etc ..) in service definition once but using new class() approach each time you have to pass dependencies manually - M Khalid Junaid
if your coworker wrote the code, then you should have this discussion with them first. maybe there's a good reason they're using new - FuzzyTree
Instantiating the service by hand really defeats the purpose of a DIC. Also it makes testing harder because you can't inject a mocked service. So stick to the first, and rather change the second usage. - Yoshi
@FuzzyTree I already did, there is no reason. He's new with Symfony so he wrote the code "the old way" - Xavier

2 Answers

3
votes

If the service is defined in the Ioc container, then by all means use it from there, because it will be constructed by the container. It takes the responsibility of instantiating new classes away from the developer. If the explicit dependencies change, you will only need to change them in container, not hunt them in the whole project code. This also in most cases has the performance benefit, because some classes need to be instantiated only once. In any way, talk to your co-worker, why he does it like this.

2
votes

I always use the first way (ie. using the service container) because with Symfony's dependency injection you don't need to worry about dependecies and/or parameters; I've never used the second way (ie. instantiating a service "by hand" with the new keyword) and I'm pretty sure that it is the worst way.

By the way, you should check out the official "best practices" guide and these blog posts by Fabien Potencier.