Php dependency injection

Php


Categories

JavaScript Design Patterns PHP jQuery MySQL Databases WordPress Algorithms HTML

Tipo IT - where your web applications live

Here we will try to show an example comparing a regular Php code implementation (using new or singleton pattern), and using dependency injection instead of invoking object via new or singletons.

Let us look at this example:

php-dependency-injection

Regular way of doing things would be:

php-dependency-injection

Suppose that we want to use the Service2 object instead of Service1 object now. We must change the code of SomeNewService, and all other classes that use this code.

With dependency injection:

php-dependency-injection

Now, we have services defined using an interface:

php-dependency-injection

Using dependency injection and programming to an interface when building larger, scalable projects can potentially solve many problems with object changes and unit testing which you might encounter using regular coding practices where you invoke new object wherever you need it in your code. For example, if we change a property of one class that we use in another class as a dependency, you might find yourself correcting all the instances of the original class everywhere in your code. Moreover, testing a class that contains another class, can present a problem, and your unit tests might start behaving badly (essentially you are testing two objects instead of one in multiple occurrences in your code). Dependency injection, if utilized properly, can eliminate these headaches in a big project.

back to articles...