Avoid long argument lists in the symfony constructor service

I use Symfony to develop my web applications, but I have a problem all the time. I always get too much mess in the constructor of my services, because I want to be able to unit test my services correctly.

Theoretical use case

Let's say I need a service that allows me to process an XML file and save its contents in a database.

<?xml version="1.0" encoding="UTF-8" ?>
<users>
    <user>
        <id>1234</id>
        <username>Example User</username>
        <email>user@example.com</email>
        <usergroup>
            <id>567</id>
            <name>Example User Group</name>
        </usergroup>
        <permissions>
            <item>ALLOWED_TO_CREATE</item>
            <item>ALLOWED_TO_UPDATE</item>
            <item>ALLOWED_TO_DELETE</item>
            <item>ALLOWED_TO_view</item>
        </permissions>
    </user>
</users>

Already comes a lot of things that you need to enter into this service:

  • DomCrawler (for reading an XML file)
  • UserRepository (to get existing users)
  • UserGroupRepository (to get existing user groups)
  • PermissionsRepository (to obtain existing permissions)
  • EntityManager (to save en flush new / updated objects)

XML, , , , , .

1: Doctrine

Doctrine $doctrine->getRepository(User::class)

Pros

  • , , , .

2:

services.yml

services:
  AppBundle\Service\MyImportService:
    calls:
      - [setUserRepository, ['@app.user_repository']]

Pros

  • ,

, unit test?

?

+4
1

- , . , , (SRP). SRP , .

Injection , , , , , . , Injection - .

. , :

[ , , Parameter root, Facade . , , .

:

:

+4

Source: https://habr.com/ru/post/1682029/


All Articles