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

Brandon Savage:
Avoiding Setter Injection
Oct 15, 2018 @ 16:11:38

Brandon Savage has a tutorial posted to his site covering the use of setter injection, some of the issues that can come with using it and how to avoid it.

PHP more or less has two kinds of dependency injection available: constructor injection, and setter injection. Constructor injection is the process of injecting dependencies through the constructor arguments. The dependencies are injected via the constructor, on object creation, and the object has them from the very beginning.

Setter injection is different; instead of providing the dependencies at construction time, the dependencies are provided via setter methods, once the object has been constructed. This allows the flexibility to configure the object during the runtime, rather than at construction.

He goes on to point out two flaws with setter injection: "half-baked" objects and the injection of potentially unused objects/resources. He spends the remainder of the post covering each of these topics more specifically and wraps it up with a recommendation to avoid it if possible and opt for useful, "fully baked" objects injected via the constructor instead.

tagged: tutorial avoid setter injection object halfbaked extra object resource

Link: https://www.brandonsavage.net/avoiding-setter-injection/

PHPBuilder.com:
Using Dependency Injection in PHP
Mar 03, 2017 @ 16:05:37

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.

tagged: dependency injection tutorial introduction setter constructor container property

Link: http://www.phpbuilder.com/articles/application-architecture/design/using-dependency-injection-in-php.html

SitePoint PHP Blog:
How to Make Modern PHP More Modern? With Preprocessing!
Feb 03, 2017 @ 17:20:47

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 article Christopher 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.

Let’s have a bit of fun. A while ago, I experimented with PHP macros, adding Python range syntax. Then, the talented SaraMG mentioned an RFC, and LordKabelo suggested instead adding C#-style getters and setters to PHP.

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.

tagged: precompile macro tutorial language feature getter setter

Link: https://www.sitepoint.com/how-to-make-modern-php-more-modern-with-preprocessing/

QaFoo.com:
Never Use null
May 03, 2016 @ 18:07:32

On the QaFoo.com blog they've made a recommendation in their latest post - they suggest that you never use null.

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.

tagged: never use null return value injection setter solution suggestion debugging

Link: https://qafoo.com/blog/083_never_use_null.html

ThePHP.cc:
How to Validate Data
Nov 10, 2015 @ 16:18:52

In this post to thePHP.cc site Sebastian 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.

tagged: data validation object recommendation setter business rules

Link: https://thephp.cc/news/2015/11/how-to-validate-data

MaltBlue.com:
Easy Setter Injection in Zend Framework 2
Jan 30, 2014 @ 17: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

Allan MacGregor:
Playing with dependency injection in PHP
Jan 07, 2014 @ 16:08:10

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.

tagged: dependency injection constructor setter tutorial introduction

Link: http://coderoncode.com/2014/01/06/dependency-injection-php.html

7PHP.com:
Auto Generate Properties Dynamically For Your Classes Using Magic Methods & Reflection
Oct 28, 2013 @ 17:57:14

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 Wasseem has 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.

tagged: reflection getter setter private property tutorial trait inheritance

Link: http://7php.com/magic-dynamic-properties/

Russell Walker:
Public properties, getters and setters, or magic?
Sep 26, 2013 @ 14:58:36

Russell Walker has a recent post to his site looking at different ways to work with class properties including using them as public properties or using getters and setters.

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.
tagged: class property getter setter magic public opinion

Link: http://russellscottwalker.blogspot.co.uk/2013/09/public-properties-getters-and-setters.html

Matt Frost:
Dependency Injection Container Question
Feb 18, 2013 @ 15:26:17

In his latest post Matt 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.

tagged: dependency injection container manual constructor setter

Link:


Trending Topics: