The PHPBuilder.com site has posted a tutorial talking about dependency injection in PHP applications covering not only the use of dependency injection (DI) containers but also constructor, setter, property and reflection based injection methods.

Dependency injection is a software design pattern that implements the inversion of a control concept for resolving dependencies. According to this concept, a class should not configure its dependencies statically, but should be configured from the outside.

A dependency is an object that can be used (a service) and an injection is the passing of a dependency to a dependent object (a client) that would use it. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

The tutorial starts out with a simple example of a set of classes that depend on each other through the creation of internal objects. They then show how the different types of dependency injection can help reduce these dependencies with brief descriptions and sample code for each. The final example, a dependency injection container, gives a quick example but also links to several package options you could pull into your application including Pimple, Aura.Di and PHP-DI.

The SitePoint PHP blog has posted another tutorial from author Christopher Pitt sharing another one of his "interesting things" you can do with PHP. In this latest articleChristopher returns to the idea of "macros" to help with some pre-processing in PHP applications and, ultimately, creating a new language feature without some of the usual overhead.

Aware of how painfully slow it can be for an outsider to suggest and implement a new language feature, I took to my editor…

He starts with a brief refresher on macros to do some pre-processing on PHP scripts and allow you to make custom language features that then get interpreted into valid PHP (often with some interesting eval tricks involved). He starts by building a "base" to add in the C# style getters and setters in a special format inside of a class. He includes the macro definitions to set this up and the result once it is passed through the "yay" precompiler. To get around having to run that precompiler every time manually, he creates a custom autoloader to do the job dynamically. He then takes this logic and packages it up so it can be easily installed as a Composer dependency. With this structure in place, he moves on to the creation of a new language feature - the actual functionality for the getter/setters. He ends the post with a screen capture showing the language feature in use and some of the interesting things you can do with it.

When doing code reviews together with our customers we see a pattern regularly which I consider problematic in multiple regards – the usage of null as a valid property or return value. We can do better than this.

Let's go into common use cases first and then discuss how we can improve the code to make it more resilient against errors and make it simpler to use. Most issues highlighted are especially problematic when others are using your source code. As long as you are the only user (which hopefully is not the case) those patterns might be fine.

They talk about some of the most common uses they see for using null in PHP applications including setters for class properties (injection). They point out that in PHP 7 a missing value on a property would result in a Fatal error and make the functionality harder to test overall. They suggest that all required dependencies be injected on object construction instead, making it easier to know the current state of the object on testing. They also talk some about using null as a return value, how it could make debugging difficult and a solution that could make more sense - throwing an exception instead.

In this post to thePHP.cc siteSebastian Bergmann looks at validation data, both in the sense of user input and the contents of objects you're application is currently working with.

Validating data seems to be one of the most important tasks of an application. After all, you cannot trust data from external sources. So let us have a look at how to efficiently implement data validation.

He gives an example of a user profile with requirements on the data it should contain. He focuses on the email address property as it's one of the easier options to validate (or is it). He walks through the usual progression from controller injection to setter injection of the value but wonders when the validation should happen to keep the Profile object from becoming invalid. He points out that simply having a validate method perform the checks isn't enough as it may not always be called correctly, leading to potentially invalid objects. Instead he recommends an alternative - using a validator object/tool in the setters of your object instance as the values are set. This prevents the object from getting into an unknown state and provides immediate feedback to the developer when something's wrong.

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.

Allan MacGregor has a recent post to his site looking at the use of Dependency Injection in PHP applications. He covers two main methods, constructor injection and setter injection, and code examples of each.

By using Dependency Injection we can write more maintainable, testable, and modular code. All projects have dependencies. The larger the project the more dependencies is it bound to have; now having a great number of dependencies is nothing bad by itself however how those dependencies are managed and maintained is.

Dependency Injection is not a new pattern and it has been commonly used on many languages like Java, but this pattern is somewhat new in the PHP world and it's gaining traction quickly thanks for frameworks like laravel.

He starts with a class that has no dependency injection, hard-coding dependencies inside the constructor. His first refactor shows how to take this class and use constructor injection to pass in an instance of an object rather than a value. After briefly explaining this method, he moves on to setter injection. He shows how to use a "setter" method to inject the needed object.

Accessing private class properties via getters and setters is a pretty standard way to write your applications. Unfortunately it can be time consuming to write them for every property your class may have. On 7PHP.com Khayrattee Wasseemhas a few ideas (including using PHP's own Reflection functionality) to dynamically create them.

When coding a project, at times (or most of it?) some classes might have more than 3 fields (for whatever reason it suits you). So instead of each time writing and repeating setters and getters (accessor methods), I would like to have a piece of reusable code for all my classes without me ever writing a single line of code for accessors. (‘ever’ as in ‘very very rarely’). Now, we also have to take into consideration that some fields might be only get-able or only set-able – (our re-usable piece of code should cater for this)

He shows two different methods to accomplish this kind of dynamic access, one using traits and the other using normal class inheritance. HE includes the code illustration each solution and talks a bit at the end of each section of why that method might be better than the other.

Opinion seems to be divided on whether it is good practice to use public properties in PHP classes, or whether to use getter and setter methods instead (and keep the properties private or protected). A sort of hybrid third option is to use the magic methods __get() and __set(). As always, there are advantages and disadvantages to each approach, so let's take a look at them.

He breaks the rest of the post up into three sections, each with a bit of a code example and the common advantages/disadvantages. It's a good overview of the three types and, in the end, it's mostly about what works for your applications. What's his favorite?

My choice then is to use public properties most of the time, but getters and setters for critical settings that I feel need stricter control, would benefit from lazy loading, or that I want to expose in an interface.

In his latest postMatt Frost takes a look at dependency injection. He thinks out loud about some of the common uses for it but wonders if there's a middle ground for using a DIC and injecting manual dependencies.

The question I have is what if a dependency in one class also has a dependency? To illustrate what I mean, here's an example with some code to follow. [...] I'm not really concerned about the code here as much as I am about the concept that I'm trying to illustrate, in order to use a dependency injection container for this scenario.

In his example code, he shows a "DBAuthMethod" class that extends the "AuthMethod" interface and an "Auth" class that requires an instance of "AuthMethod" as a constructor parameter. He wonders about constructor versus setter injection and thinks that a mix of the two may not be the best structure for the code.

I just can wrap my mind around a scenario where you could ONLY use a DIC, and if you can't use the concept exclusively what benefit is there to using it?

Have any suggestions to share? Let him know - this is a problem more and more developers run into as DIC becomes more widely used.

In application development, we try to create independent modules so that we can reuse code in future projects. But, it’s difficult to create completely independent modules which provide useful functionality; their dependencies can cause maintenance nightmares unless they are managed properly. This is where Dependency Injection comes in handy, as it gives us the ability to inject the dependencies our code needs to function properly without hard coding them into the modules.

They start with a look at the problem with working with "concerete dependencies", ones that are hard-coded into your classes making them not only hard to test but potentially difficult to maintain. They include an example of this (a "SocialFeeds" class and friends) and then one of two ways to fix the situation. They start with using constructor-based injection, injecting the Twitter service into the main feeds object. They also talk about another method - setter-based injection - where the objects are injected via specific methods on the object.

As a third alternative, though, they get to using Pimple to manage the objects, making it easier to inject just the one resource into your classes and extract the objects you need from there. There's also a bit of "advanced" usage of Pimple showing the use of the "share" and "extend" methods.