Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Matthias Noback:
Road to dependency injection
Jun 12, 2018 @ 09:31:59

In a new post to his site Matthias Noback walks you down a road to dependency injection, sharing his process of migrating a codebase from static calls to a more modern, robust dependency injection pattern.

I've worked with several code bases that were littered with calls to Zend_Registry::get(), sfContext::getInstance(), etc. to fetch a dependency when needed. I'm a little afraid to mention façades here, but they also belong in this list. The point of this article is not to bash a certain framework (they are all lovely), but to show how to get rid of these "centralized dependency managers" when you need to.

He talks about this common use case of "statics everywhere" and some of the problems with coupling your code to a static way of doing things. He walks through the steps towards modernization including injecting the container itself into the controller and shifting logic out into services. He also makes suggestions on what to do when constructor injection isn't possible and how to deal with "temporal coupling".

tagged: dependencyinjection refactor codebase static inject container tutorial

Link: https://matthiasnoback.nl/2018/06/road-to-dependency-injection/

Matthias Noback:
Reducing call sites with dependency injection and context passing
Jan 31, 2018 @ 11:15:40

Matthias Noback has posted a continuation of his previous article covering unary call sites and interfaces with this new tutorial with a way to reduce these call sites by making effective use of dependency injection and passing values with the correct context.

While reading David West's excellent book "Object Thinking", I stumbled across an interesting quote from David Parnas on the programming method that most of us use by default [about the process a machine uses to execute code]. It may seem like a very logical thing to do. And it's what I've seen myself and many other programmers do: "How do we implement this feature?"

[...] I described one situation in a previous article about read models, where I realized that we often try to answer many different questions by querying one and the same model (which is also the write model). By splitting write from read, we end up with a more flexible design.

The same goes for introducing interfaces, to achieve dependency inversion. We do a little extra work, but we thereby allow ourselves to get rid of a bit of "computer think".

He goes on to talk about singletons, service locators and registries and how dealing with them can get complex relatively quickly. He then shares a few possible solutions in the form of dependency injection and passing in the items needed for context rather than pulling them from another object. He ends the post with a summary of the combination of these two methods, showing how they can reduce the number of overall "call sites" for pieces of functionality in your application.

tagged: callsite dependencyinjection context passing tutorial series part2

Link: https://matthiasnoback.nl/2018/02/reducing-call-sites-with-dependency-injection-and-context-passing/

Russell Walker:
Is Best Practice Actually Poor Practice? Dependency Injection, Type Hinting, and Uni
Apr 05, 2017 @ 13:26:03

Russell Walker has a post to his site sharing his thoughts defending dependency injection, type hinting and unit testing against some of the common objections.

I've recently been in discussion with a colleague who thinks that dependency injection (DI) is over-used and, in cases where the dependency is a concrete class, unnecessary (in the latter case, he advocates simply creating new objects on the fly).

[...] In my opinion, this line of thinking is misguided, but he sent through some links to pages that he felt supported his point of view (including Tony Marston's rant on DI, and the Laravel documentation about 'facades' - which are actually used as an alternative syntax for the service locator [anti-]pattern). I genuinely wanted to understand the reasoning behind his point of view, as it flies in the face of just about everything I have ever read regarding best practice in PHP development. After reading those resources he sent though, I began to notice some misconceptions about what unit testing actually is, as well as confusion about the difference between code that is "strongly typed" (usually good) and "tightly coupled" (usually bad), and also a tendency to blame the wrong thing when problems arise.

He then breaks the rest of the post down into a few of the common objections and makes an attempt to set the record straight:

  • Not All Automated Tests Are Unit Tests
  • Using Mocks to Test in Isolation
  • What, Never Ever Create Objects on the Fly?
  • What About Those Laravel Facades?
  • Hidden Dependencies and Other Dangers
  • Strongly Typed is not Tightly Coupled

He ends the post with "another reason" that there could be issues with developers dismissing best practices in their development - a misunderstanding of the principle and how to correctly implement it.

tagged: bestpractice dependencyinjection typehint unittest opinion

Link: http://russellscottwalker.blogspot.co.uk/2017/03/is-best-practice-actually-poor-practice.html

QaFoo Blog:
Getting Rid of static
Jan 12, 2017 @ 10:46:41

On the QaFoo blog today Kore Nordmann has posted a suggestion that could make your unit testing life simpler: get rid of statics (variables, methods, etc).

When people start (unit-)testing their code one of the worst problems to tackle are static calls. How can we refactor static calls out of an existing application without breaking the code and while producing new features? How can we get rid of this big test impediment?

They illustrate the main problem with a simple UserService class that contains a static function which, in turn, uses static calls to a Cache and a DB class. The major issue is that, when the static getUser method is called there's not a way to mock the Cache or DB classes, resulting in the actual handlers being called. They offer three things you can do to help refactor away from using static methods:

  1. Replaceable Singletons
  2. Service Locator
  3. Dependency Injection

For each item on the list a brief explanation is provided of what it is and how it helps you get away from the singletons scattered throughout your codebase (and how it makes things easier to test).

tagged: static refactor unittest testing singleton servicelocator dependencyinjection

Link: https://qafoo.com/blog/094_getting_rid_of_static.html

Patrick Louys:
The Open/Closed Principle
Dec 14, 2016 @ 12:12:33

Patrick Louys has written up a new post to his site that gets into detail about one of the SOLID development principles - the Open/Closed Principle - and how it can be applied in PHP.

I am a big proponent of the SOLID principles. But one of the principles - the open/closed principle - is often misunderstood. [...] Bertrand Meyer stated it first in his book "Object-Oriented Software Construction" in 1988. The problem with it is that some people see the word extension and they think that it is talking about inheritance (because PHP uses the extend keyword for inheritance).

He goes on to talk about a comment from Reddit and uses it as an illustration about the "extension" misconception and the commentor advocating against dependency injection. He then gets into some code showing a "Logger" class that writes to the filesystem and trying to extend it to add functionality. He covers how using a dependency injection container can help some of the inheritance issues (using a "base" class) but ultimately steps back to provide another solution. The re-applies both the open/closed principle and dependency injection to create a system where the "base" Logger class is a dependency rather than a parent class.

tagged: openclosed solid principle dependencyinjection application inheritance

Link: http://patrick.louys.ch/2016/12/11/open-closed-principle/

Decouple Your Framework for Easy Replacement
Aug 12, 2016 @ 11:14:12

In this recent post to the In2it blog Michelangelo van Dam makes a recommendation to decouple your logic from your framework to make it easier in the future if you need to replace it.

Decouple your framework or library from your business logic for future upgrades or replacements through usage of interfaces. By separating your business logic completely from the tool used to glue all things together, you can replace your framework or upgrade to a newer version without much problems.

He talks about how it's common for applications to quickly become "good application turns into a cluster of code on top of a cluster of code". While the title suggests completely swapping out the underlying framework, he shifts it to talk more about updates to the current framework, especially ones that would break non-decoupled functionality. He then covers the ideals of "interoperability" between PHP packages based on common interfaces (like the PSRs) and how following a similar idea can help decouple your code to prevent hard work for future potentially breaking changes.

tagged: framework replacement changes interoperability dependencyinjection example

Link: https://www.in2it.be/2016/08/decouple-framework-library-easy-replacement/

Shameer C:
Automatic construction injection in Slim 3
Oct 20, 2015 @ 11:09:38

Shameer C has a post to his site showing you how to automatically inject values in constructors on Slim 3 based applications. This makes use of the inheritance of constructor parameter functionality the Aura.DI container makes available.

In the previous blog post we have discussed how to replace the default Pimple Container with Aura.DI in Slim framework 3. Aura.DI gives us more flexibility in terms of managing dependencies. We saw one most useful feature in Aura.DI, Inheritance of constructor parameters, that will help us to avoid repeating common parameters for Controllers and Models. In this article we will see another advantage of the same feature.

He gives an example of how, with the default DI container in Slim (Pimple) you have to make a new instance of a class manually each time you need it. He talks about how Slim 3 internally resolves controller classes (using a CallableResolver) and a small change that can be made to prevent you from needed to define every constructor into the DI container and allow for more dynamic handling.

tagged: automatic injection constructor callableresolver slim3 tutorial auradi dependencyinjection

Link: http://blog.shameerc.com/2015/10/automatic-construction-injection-in-slim-3

Marc Morera:
Defeating Expression Language
May 18, 2015 @ 08:38:27

Marc Morera has a new post to his site wanting to help you defeat Symfony's expression language and perform the same functionality, just more on the code side (another option).

How beautiful Expression Language definitions are, right? I mean, inserting that complex expressions in a Dependency Injection configuration file is so nice and fast if you need to inject the result of a method in a service (one of the multiple examples we can see). [...] This is not a bad idea, really, but because we are engineers and we should have as much information as possible in order to be able to choose between the best option, always, I will show you another way of defining this piece of code.

He shows how to write some code using the Factory design pattern structure to reproduce a bit more complex piece of expression language. He shows the setup of the services.yml file to define the "managers" and classes/services to be injected. He also notes that this removes the need for the "symfony/expression-language" dependency and makes things more portable in the future.

tagged: expression language symfony alternative factory dependencyinjection services configuration

Link: http://mmoreram.com/blog/2015/05/18/defeating-expression-language/

David Lundgren:
When does Dependency Injection become an anti-pattern?
Apr 23, 2015 @ 12:11:53

In a new post to his site David Lundgren wonders when dependency injection becomes an anti-pattern when used in PHP applications. The idea of dependency injection is to provide objects with instances of other objects representing things they'll need to get the job done (goes along with separation of concerns). Unfortunately, if used incorrectly, DICs - dependency injection containers - can become less useful and more of a hinderance than a positive part of the application.

During my tenure as a seasoned, and tenderized, PHP developer I have used many design patterns: adapters, factories, data mappers, facades, etc. The most recent one that I have been working with is Dependency Injection. Inversion of Control is not a new idea, at least not in the programming world, but in the PHP world it seems to have taken us by storm in recent years. Every framework will often have a Dependency Injector built in, or offer it as a component for use. It is the hip thing to do in PHP, but I believe we need to take a step back and evaluate it for what we are really trying to achieve. That is reducing the tight coupling that our objects may have. I view it as removing the new-able’s from our objects code, and handing the object creation over to something else to deal with.

He talks about how dependency injection containers and service locators relate to each other. He also suggests that, at the heart of every dependency injection container, there's a service locator. He gives an example of a project where a large number of dependencies are being injected and how, despite the assumption of flexibility, his dependencies don't change that often, making the DIC and its functionality a bit less important.

tagged: dependencyinjection dic servicelocator antipattern designpattern opinion

Link: http://davidscode.com/blog/2015/04/17/when-does-dependency-injection-become-an-anti-pattern/

Trait injection in Zend Framework 2
Dec 11, 2014 @ 11:55:56

Boban Acimovic has recently posted a tutorial showing you how to use traits in a Zend Framework 2 application to inject additional functionality into your pre-existing classes.

There are several tutorials on the Internet which explain how to use interface based dependency injection in Zend Framework 2. The idea is to make an initializer, figure out which interfaces a class implements and then inject appropriate dependencies using setters defined in the interfaces. Bad part about this is that in each class you implement such an interface you have to declare a property which would hold the injected object and also to implement the setter for it, which is defined in the interface, by the way. In order to simplify this further it is possible to write trait for each interface, but then why should not use just traits? Why do we need interfaces? Is this possible at all?

He includes some example code showing how to set up dependency injection for the traits (via a custom injector based on the "InitializerInterface") and make the autoloading easier. He shows how to add this to the provider configuration as an "initializer" and create the first example trait, a checker for data in user passwords. He then drops the functionality into a service class just by using the "use" keyword and the trait name.

tagged: trait injection zendframework2 tutorial dependencyinjection service provider

Link: http://www.acim.net/2014/11/trait-injection-in-zend-framework-2/