samedi 1 février 2020

Resolving dependencies without a dependency injection container

I have a project in plain PHP and there is a class which is dependent on external library.

I don't feel like passing it to constructor everywhere is a good idea (it's called mainly in tests, but the users of the package will have to pass it to constructor).

I don't have any DI containers and don't think I should have because the project is a small package and will only have a few classes.

So I've come up with this approach and was wondering if there any consequences or drawbacks of this approach or if there any other solution to this?

    protected $client;

    /**
     * @param Client|null $client
     */
    public function __construct(Client $client = null)
    {
        $this->client = $client ?? new Client();
    }

Aucun commentaire:

Enregistrer un commentaire