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

Laravel News:
Laravel 5.5 Custom Validation Rule Objects
Jul 17, 2017 @ 10:20:40

On the Laravel News site there's an article covering custom validation objects and using them in a Laravel-based application. This validation handling is added in Laravel v5.5 (upcoming as of the time of this post) to allow for easy extension of current validation rules.

Laravel 5.5 will introduce support for custom validation rule objects as an alternative to using Validator::extend for custom validation rules.

To define a custom validation rule, implement the IlluminateContractsValidationRule interface or use a Closure. The custom rule is then used directly in a validator.

They provide a few examples of defining these objects, using the "passes" and "message" methods defined in the interface. It also shows how to put them to use in a "validate" call on a request using both the object and closure versions. This new custom validation handling helps to replace some of the difficulty with the previous extension methods and makes it more flexible by allowing closures.

tagged: laravel custom validation object introduction closure tutorial

Link: https://laravel-news.com/custom-validation-rule-objects

Simon Holywell:
PHP and immutability - part two
Apr 04, 2017 @ 12:54:48

Simon Holywell has continued his series looking at immutability and PHP in part two of his series improving on the code and classes from the previous post.

In the last article we learnt how to create an immutable data structure in PHP. There were a few issues to work through, but we got there in the end. Now onto making the immutable class more useful and easier to create modified copies. Note that these are copies and not modifications, in-place, to the original objects.

He then moves on from the "simple" mutation method previously used (making a new immutable object when a property changes). When the property list starts getting more complex simple single value references no longer scale. He makes use of methods internal to the class to modify the values and return a new immutable instance with the updated value. He shows how to modify this to prevent the setting of unexpected properties and how to expand it out to allow the input of an array of values to update and how to handle required/optional property values.

tagged: immutability series part2 tutorial immutable object

Link: https://www.simonholywell.com/post/2017/04/php-and-immutability-part-two/

Robert Basic:
PHP traits to create test doubles
Apr 04, 2017 @ 10:47:15

In a new post to his site Robert Basic shows how to make use of traits to create test doubles in your unit testing practice. He sees them as a simple method for keeping tests clean and not having mocks/fakes/etc. all over.

Keeping your application or library code well organized, easy to follow, and read is important. Your test code should not be exempt from those rules, you should follow good testing conventions.

One part of my tests that I feel like that are out of control are the test doubles. Dummies, fakes, mocks… Seems like they are everywhere and that I keep writing the same ones over and over again. I do follow some good practices on how to reduce code duplication in my tests, but these mocks… Ugh.

He starts with a simple example, showing a test that evaluates the result of a transaction being executed (true or false). However, he describes the eventual "creep" of the tests as more are added and, with each, more "transaction" object instances are required. He suggests refactoring the creation of those doubles into traits where the class they're called from can inherit them and test setup is a bit cleaner. He proposes a "trait for every double" so that they can be easily included as needed and without conflict.

tagged: traits unittest double mock tutorial example setup object

Link: https://robertbasic.com/blog/php-traits-to-create-test-doubles/

Benjamin Eberlei:
Explicit Global State with Context Objects
Mar 24, 2017 @ 11:50:12

In a post to his site Benjamin Eberlei looks at global state in PHP using something called "context objects" and how they can be used as an alternative to true global state.

Global State is considered bad for maintainability of software. Side effects on global state can cause a very nasty class of bugs. Context objects are one flavour of global state. For example, I remember that Symfony1 had a particularly nasty context object that was a global singleton containing references to very many services of the framework.

As with every concept in programming, there are no absolute truths though and there are many use-cases where context objects make sense. This blog posts tries to explain my reasons for using context objects.

He starts by getting everyone on the same page by defining a context - the "circumstances in which something can be fully understood". He then moves into the world of context objects, talking about how they encapsulate the information other objects need to execute. They're essentially "container" objects that allow for more control that something like the normal PHP superglobals. From there he helps you define what kind of context objects you might need in your application and provides a real-world example from his own experience at Tideways.

tagged: global state context object tutorial introduction definition

Link: https://beberlei.de/2017/03/12/explicit_global_state_with_context_objects.html

Mark Baker:
Closure Binding as an alternative to “use” variables
Mar 13, 2017 @ 09:56:56

Mark Baker has posted a tutorial to his site showing how to use closure binding as an alternative to "use" when calling closures in your PHP application.

As a general rule when creating a Closure, arguments are passed when the function is called, but “use” variables (I’m sure that they have a formal name, but have no idea what it might be, so I just refer to them as “use” variables because they’re passed to the Closure through a “use” clause) are fixed as the value that they already contain when the Closure is defined, and the variables themselves must already exist within that scope

[...] Of course, the drawback of this approach is that when we need to change the price minimum and maximum values for filtering, they’re hard-coded in the callback.

He talks about the limits this imposes on calling the closure (ex: can't easily add addition params) and how the values have to already exist before the closure can be called. He points out that calling the variables by reference can help somewhat but it still comes with some of the same baggage. He then shows how to use object binding for a closure to handle the same kind of "min" and "max" by working around it with a closure bound internally to an object and called via a public method.

tagged: closure bind variable object tutorial use

Link: https://markbakeruk.net/2017/03/12/closure-binding-as-an-alternative-to-use-variables/

QaFoo Blog:
Extracting Data Objects
Feb 10, 2017 @ 12:16:36

On the QaFoo blog they have a new post offering some advice on extracting functionality to data objects and reducing the complexity of your application's interfaces.

Extracting data objects from your code will make it easier to read and write, easier to test and more forward compatible. This post shows you the two most common cases where introducing a data object makes sense and how to do it.

The first case covers the extraction when a method ends up with too many parameters. We've all been there and remembering the correct order and values for each (not to mention optional vs required). By making use of value objects you can reduce that down to one or two parameters that act as self-contained "containers" for the same values. They illustrate with a refactor of "product" search criteria into a "ProductCriteria" object. The second example show a refactor away from using an array as an input value and providing a bit more structure with a "Checkout" value object instead.

The post ends with a helpful hint about migrating from one method to the other in legacy systems using a "shim" method to handle the new case right alongside the old one.

tagged: data object refactor simplicity parameters array

Link: https://qafoo.com/blog/096_refactoring_extract_data_objects.html

MyBuilder Tech Blog:
Designing Immutable Concepts with Transient Mutation in PHP
Dec 15, 2016 @ 09:46:11

The MyBuilder.com Tech blog has a new post from Edd Mann looking at designing immutable concepts in PHP with "transient mutation".

In a recent project we felt it beneficial to introduce the Money pattern. There are many good resources on this pattern, so I will delegate to those for further definition. We decided that encapsulating this into a immutable value object allowed for a cleaner API and removed the fear of any unexpected mutation bugs. However, we noticed a spike in memory and processor usage when wishing to perform many successive actions on such values i.e. summation.

In such a case, new ‘temporary’ Money objects would be instantiated upon each applied addition. As many of these objects were simply a stepping stone to generating the final result, they were just left for the Garbage collector to clean-up.

The idea of "transients" is something pulled from the Clojure language allowing for the mutation of the immutable object and returning a new immutable one....with with some controls, not free form mutation. He includes showing an example of a "Money" object that implements this concept including a "withMutable" method that handles a callback for the mutation operation.

tagged: immutable object transient mutation control tutorial

Link: http://tech.mybuilder.com/designing-immutable-concepts-with-transient-mutation-in-php/

QaFoo Blog:
Introduction To Page Objects
Sep 06, 2016 @ 11:03:17

The QaFoo blog has a post to their blog introducing page objects and how they're useful in functional testing to help provide a "decoupling" from the actual frontend.

A while ago we wrote about writing acceptance tests (end-to-end tests) with Mink and PHPUnit. While this is a great set of tools for various applications such tests tend be susceptible to changes in the frontend. And the way they break is often hard to debug, too. Today I will introduce you to Page Objects which can solve some of these problems.

The basic idea behind a Page Object is that you get an object oriented representation of your website. The Page Objects maps the HTML (or JSON) to an object oriented structure you can interact with and assert on. This is more initial work then than writing tests with PHPUnit and Mink directly, but it can be worth the effort.

They use the Mnk testing tool to simulate a browser and some previously shared functionality to lay the foundation. From there they write up a first test using a "Login" page object and processing the username/password handling of the page. They show how to implement a custom page object with a bit of additional logic and put it to use in processing the request. They also include an update when, for example, a site is switched from Twig templates to a React.js component and how the Page object would need to be refactored for the update.

tagged: page object functional test mink behat example tutorial

Link: https://qafoo.com/blog/089_introduction_to_page_objects.html

Adam Wathan:
Customizing Keys When Mapping Collections
Jul 19, 2016 @ 10:52:29

Adam Wathan has a new post to his site talking about mapping with collections and customizing the keys when injecting new data into your Laravel collections.

People often ask me, “how do I specify keys when I’m mapping a collection?”

It actually ends up being a pretty interesting topic, so I decided to cover it in a short screencast, as well as in written format below.

He shows how to translate a simple set of data into a much more slimmed down version. He points out that the "map" function could be used but it doesn't allow for setting keys. Instead he talks briefly about how the problem could be solved in Javascript (returning an object instead of an array) and how to use the "reduce" method to filter and reset the data as it goes through the array. He finishes out the post talking about learning from other languages, the "toAssoc" macro on Laravel collections and mapping the data back to an array with a custom macro.

tagged: customize key mapping collection laravel object javascript example screencast

Link: https://adamwathan.me/2016/07/14/customizing-keys-when-mapping-collections/

Stoimen Popov:
PHP: Don’t Call the Destructor Explicitly
Jun 27, 2016 @ 12:52:39

In a new post to his site Stoimen Popov makes the recommendation to not call the destructor explicitly in your code and provides some alternatives.

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++” says the documentation for destructors. [...] Well, as you can not call the constructor explicitly [...] so we should not call the destructor explicitly. The problem is that I’ve seen this many times, but it’s a pity that this won’t destroy the object and it is still a valid PHP code.

He talks about __destruct and it's role in PHP's set of "magic methods" and what they exist to do. He then gets into a few examples of what code could look like that uses a destructor and the difference between normal handling calling the destructor explicitly. The main differences is that calling it explicitly does not destroy the object, it's basically like calling any other method. He does include an interesting method for destroying the object - setting it to null - and notes that the destructor fires then too. He also points out a few interesting things about cloning objects and how object references work when setting nulls as in the previous example.

tagged: destructor explicit call object destroy null tutorial

Link: http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/