Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
Blaise Avatar asked Jun 18 '11 11:06

Blaise


People also ask

Does PHP have dependency injection?

Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.

How do dependency injection containers work?

A Dependency Injection Container manages objects: from their instantiation to their configuration. The objects themselves do not know that they are managed by a container and know nothing about the container. That's why a container is able to manage any PHP object.

What is DI in PHP?

There is a design pattern which could help and it's called Dependency Injection (DI). It allows you to inject objects into a class, instead of creating them there.

Is PHP a dependency?

An Introduction to Dependencies in PHPDependencies are PHP libraries, frameworks, and components that you can use in your web development projects. They help to make coding easier and more efficient, and most projects will rely on a number of them.


1 Answers

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).

like image 198
OZ_ Avatar answered Sep 24 '22 17:09

OZ_