Search code examples
phpidedependency-injectionphpstorm

How do I make my PHP IDE understand Dependency Injection Containers?


Current situation: I have dependencies in my project that I solve by using dependency injection. I want to take the next logic step by using a dependency injection container (DIC) to ease the management of my dependencies and to lazy-load classes.

I looked at Bucket, Pimple, and sfServiceContainer, ran some test and really appreciate how DIC’s work. I’d probably go for Pimple because of its simplicity and raw power. If I didn’t have this problem:

Due to the abstraction that DIC’s offer, the IDE I’m using (PHPStorm) no longer understands what’s going on in my code. It doesn’t understand that $container['mailer'] or $sc->mailer is holding a class object. I also tried Netbeans IDE: same problem.

This is really a problem for me because my IDE becomes useless. I don’t want to program without code hints, autocompletion and refactoring tools when dealing with classes. And I don’t want my IDE to find all kinds of false positives when validating code.

So my question is: Has anyone dealt with this problem and found a solution?


Solution

  • You can define class of the variable 'manually':

    /** @var YourClassType $mailer */
    $mailer = $container['mailer'];
    

    In PhpStorm (and by standards), use two asterisks and write the data type before the name of the variable.

    You can write the data type without the name of the variable (but not the name without the data type).