DI container and IDE integration

Reading Time: 2 minutes

Say we use a DI container directly, i.e. via functions like get() or make(), how do we achieve proper IDE support? For example I create a class instance the usual way

$server = $this->container->get(Server::class);

and I want to know what methods my Server class provides

$server->???

I could use docblocks

/** @var Server $server */
$server = $this->container->get(Server::class);

This works fine in many IDE like PhpStorm:

php-di-ide-integration-1

however the docblock is somehow annoying to me. The IDE *should* really know what class instance the variable $server is, since everything it needs to know is in the class name constant I provided as parameter for the get() function.

There might be a way using the hardly known .phpstorm.meta.php file for PhpStorm, but that one is currently some sort of under construction – at least I couldn’t get it working properly. Hopefully the PhpStorm guys will extend the documentation soon!

Once again, the PHP community provides the solution: the small but pretty cool PhpStorm PHP-DI plugin does exactly what we need! Now PhpStorm knows that $server is an instance of the Server class without me needing to do any further work:

php-di-ide-integration-2
Class name constants should be used wherever possible nowadays, however it also works with the Fully-qualified class name as string:
$server = $this
->container
->get('CarstenWindler\ApiGuy\Server');

But really, you shouldn’t do that. Please. Better just forget what I said. Forget it. Begone!

Awesome! Although actually written for the PHP-DI container, it also supports container-interop and even that crapp… I mean lovely but omnipresent Laravel App Facade sort of jun… container… thing.

I’d recommend to use DI containers directly only in very few places like Application bootstrapping or factories. But imagine you have to deal with a legacy Laravel 4.2 application which uses that awful App::make() basically EVERYWHERE, you are happy about any help.

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy

This site uses Akismet to reduce spam. Learn how your comment data is processed.