@Tobias's suggestion works fine but you should also consider a good pratice that says: "Inject only the services you need".
The point here is that you're injecting the Entity Manager to get two Doctrine repositories (tasks
& tasksInfos
), keep in mind that The Entity Manager did more that only retrieve Doctrine Repositories.
When you need a doctrine repository within your helper, you would normally inject an entity manager and then retrieve your repository. However, you're not injecting the service you need, you're injecting a manager that helps you get what you need.
Another constraint (one may consider) is that a Doctrine repository can only be retrieved through an Entity Manager, so we don't have any control over its construction.
So, the only way to inject your repositories instead of depending on the Entity Manager is to consider using Factory services and methods to delegate the creation of services and then inject the relevant services.
I would then suggest,
namespace Acme\MyBundle\Helper;
// Add the relevant use(s) here ...
class AnyGivenService
{
protected $taskRepository;
protected $taskInfoRepository;
public function __construct(TaskRepository $taskRepository, TaskInfoRepository $taskInfoRepository)
{
$this->taskRepository = $taskRepository;
$this->taskInfoRepository= $taskInfoRepository;
}
public function doSomethingWithYourRepositories()
{
// ....
}
}
While you service definition should looks like,
<service id="any_given_service" class="AnyGivenService">
<argument type="task_repository" />
<argument type="task_info_repository" />
</service>
<service id="task_repository" class="TaskRepository" factory-service="doctrine.orm.entity_manager" factory method="getRepository">
<argument>Task</argument>
</service>
<service id="task_info_repository" class="TaskInfoRepository" factory-service="doctrine.orm.entity_manager" factory method="getRepository">
<argument>TaskInfo</argument>
</service>
The advantages,
- Your code is clean and more readable as the constructor of you your service is more specific about its real needs.
- Testability, Instead of creating a mock for both the entity manager and the repositories, you only have to mock your repositories.