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

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

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/

Matthias Noback:
Decoupling from a service locator
Nov 12, 2014 @ 09:58:06

In his latest post Matthias Noback shares a few hints on how yuo can decouple from using a service locator in your application. A service locator (much like a dependency injection container) is a centralized place for storing and creating instances of objects in your apps with a bit more structure than just random "new" calls.

"Decoupling from a service locator - shouldn't that be: don't use a service locator?" Well, not really, since there are lots of valid use cases for using a service locator. The main use case is for making things lazy-loading (yes, you can also use some kind of proxy mechanism for that, but let's assume you need something simpler).

He starts with an example dispatcher class and shows how to modify the flow so that "expensive" listeners are only created in the correct context. He also suggests a few other methods for handling the idea of dependency inversion a service locator provides: using closures/callables instead of classes and using something called a "synthetic service", one set up at runtime as synthetic and used as needed on a manual basis (like in his bundle example).

tagged: decouple servicelocator dependency closure synthetic class tutorial

Link: http://php-and-symfony.matthiasnoback.nl/2014/11/decoupling-from-a-service-locator/

Easy Setter Injection in Zend Framework 2
Jan 30, 2014 @ 11:54:40

Matthew Setter has a new post today looking at setter injection of dependencies in a Zend Framework v2 based application. He shows how to do it via ServiceManager-aware interfaces.

For configuring objects, reused throughout the application, I’ve found it to be nothing short of amazing. With next to no code, one Module configuration setting, along with the magic of OOP, classes are suitably initialized throughout the application, without any hands-on configuration on my part. Whilst Zend Framework 2 is great without this. When you start using setter injection, it becomes so much more. In today’s post, I’ll take you through an example which uses setter injection to ensure that the AuthService, or authenticated user object is always available to a class and any of its descendants.

He walks you through a basic implementation, showing the creation of the "AuthAwareInterface" interface class and an implementation of it, the "CacheableTable". In the "CacheableTable" there's a setter and getter for the currently authenticated user. Using these he's able to configure the ServiceManager to get the AuthService instance from the service locator and inject it into the class. He also includes a word of warning to be careful with the injection you do use, pointing out that it can lead to difficult to track bugs and issues down the line.

tagged: zendframework2 setter injection servicemanager servicelocator tutorial

Link: http://www.maltblue.com/zend-framework/easy-setter-injection-in-zend-framework-2

Paul Jones:
The Difference Between Factories, Registries, and Service Locators
Dec 03, 2013 @ 10:55:09

In his past few posts Paul Jones has been looking at dependency injection versus service locators. In this new post he continues on the topic comparing three methods for working with objects - factories, registries and service locators.

In last week’s episode of this unexpected series, I said, “Go ahead and use Service Locator, but make sure each Locator contains only one type of object. This condition of restraint will keep a single locator from becoming a menace.” [...] The “only one type of object” constraint generated some discussion regarding factories and registries. [...] The differences between factories, registries, and containers (both service locators and dependency injection containers) can be subtle and hard to grasp at first. Here’s how I keep them straight.

He breaks them down with a simple definition for each related to how the object is created and its intended purpose. He also includes an example of a service locator he's created and a snippet of example code showing it in use.

Again, I must stress: Service locators can easily get out of control. If you can avoid using a service locator, you should.
tagged: factory servicelocator registry difference example code

Link: http://paul-m-jones.com/archives/4800

Ralph Schindler:
DI, DiC, & Service Locator Redux
Oct 11, 2012 @ 10:43:38

In his latest post Ralph Schindler takes another look at the usefulness of Dependency Injection Containers and whether or not they're the right thing to use for your situation.

To DiC, or not to DiC: that has seemed to be the question in PHP for the last few years. Most people generally agree that injecting dependencies is the right thing to do. For those writing a framework, or any shared codebase where extensibility or the ability to grow the codebase is a core philosophical tenet, not injecting dependencies is doing a disservice to the project in the long run. So, as I’ve stated before, the question becomes how do we manage the added complexity that comes with practicing dependency injection?

He briefly covers two topics that are often confused - the concepts of a service locator and a true dependency injection container. He then talks about the more correct situations to use each of them, mentioning a few questions you can ask about your app to determine the best fit. To illustrate, he includes a simple example where he mixed the two - DIC for models and service location for the controllers.

tagged: dependencyinjection container servicelocator example dic


Managing Class Dependencies: Dependency Injection, Service Locators & Factories, Pt 2
Jun 28, 2012 @ 10:58:15

PHPMaster.com has posted the second part of Alejandro Gervasio's series looking at dependency injection, service locators and factories. In this new part of the series, he picks back up with his look at these patterns and how they can reduce your dependencies on things like "new" even more.

While it’s fair to admit that factories do have a neat niche in a number of special use cases, I’m not so merciless as to condemn Service Locators and plain Dependency Injection to an unfair exile. In this final part we’ll take a closer look at the implementation of these popular patterns so that you can pick up the one that best suits the need at hand.

He talks some about "class collaborators" as used in service locators and using it in his FileStorage example to find and use pre-created objects. He compares this method with a more simple dependency injection approach, noting that not only is it simpler to maintain but also can cause less overhead required for the DIC.

tagged: class dependencies series dependencyinjection servicelocator


Chris Hartjes' Blog:
DIC vs. Service Locator
Jun 07, 2012 @ 10:09:36

In a new post to his blog, Chris Hartjes shares one thing that you can use to make your code easier to test - using a dependency injection container and how it compares to a service locator.

People often ask me what’s the one thing they could do for their code base RIGHT NOW that will make it easier to test. To me, the answer is simple: make sure you are using Dependency Injection (yes the link is long and has code samples in Java, but whatever). Without the ability to “inject” your dependencies into your code (whether it is class methods or functions) you will have problems testing modules of code in isolation from each other.

He shows the possible uses of DICs, including code samples, and talks the differences between the two. He explains that the real difference in them is how its being used. When it's used to add and remove instances, it's a container. When its actually put to use and passed into a class, it morphs into a service locator.

tagged: dependencyinjection servicelocator testing difference