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

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 2)
Aug 11, 2017 @ 10:44:19

Mark Baker has posted the second part of his series covering the use of closures and anonymous classes as an alternative approach to mocking in your unit tests. In part one he introduced some of the basic concepts behind their use and in this latest post he focuses on "different approach to using an Anonymous Class to verify the values of object properties".

The last time I posted here, I was writing about Anonymous Functions and how they can be bound to any object (or class) to execute as though they are a method within the scope of that class (Closure Binding as an alternative to “use” variables); and in the first article in this series, I looked at using a Closure to access private and protected properties of an object.

I was going to write this particular article about using simple Anonymous Classes to create test doubles for Unit Testing – and may well return to that topic in a future article in the series – but Matt Brunt has written a good post on that topic already, so instead I’m going to focus on a different approach to using an Anonymous Class to verify the values of object properties that we otherwise couldn’t see directly when testing a class.

He goes on to talk about some ideas from the Java ecosystem around nested classes and scoping. He then shows how, with closure binding, the same kind of effect can be created in PHP testing. He includes the code for an example of a class that coverts distance measurements. He then introduces his "SpyMaster" utility class that "infiltrates" the class under test and attaches the closure providing the needed point for testing. He finishes up the post talking about this functionality and how the technique can be used in many places, not just testing class constructors.

tagged: closure anonymous class alternative mock tutorial part2 series

Link: https://markbakeruk.net/2017/07/30/closures-anonymous-classes-and-an-alternative-approach-to-test-mocking-part-2/

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

Robert Basic:
Complex argument matching in Mockery
May 09, 2017 @ 10:40:15

Robert Basic has written up a new tutorial for the unit testers out there showing how to do some complex argument matching in Mockery, a popular testing tool that offers an alternative to PHPUnit's own mocking functionality.

This past weekend I did some issue maintenance and bug triage on Mockery. One thing I noticed going through all these issues, is that people were surprised when learning about the Mockery::on() argument matcher. I know Mockery’s documentation isn’t the best documentation out there, but this still is a documented feature.

He starts with a simple mock example, mocking out AClass and defining two method criteria (one with a once and another with a never). He points out that things are not always that simple and sometime more complex argument matching is required. The Mockery:on handler allows you to pass in a closure and do more complex evaluation of the values passed in. He includes an example of this, evaluating the result of a set of arguments passed in and ensuring they're all set.

tagged: complex mocking mockery argument tutorial on method closure tutorial

Link: https://robertbasic.com/blog/complex-argument-matching-in-mockery/

Matthew Weier O'Phinney:
Using Anonymous Classes to Write Middleware
Apr 03, 2017 @ 11:22:48

Matthew Weier O'Phinney, lead developer on the Zend Framework project, has written up a new post for his site showing how to use anonymous classes to write middleware for your applications (several frameworks support the concept of middleware these days).

I faced an interesting question recently with regards to middleware: What happens when we go from a convention-based to a contract-based approach when programming?

Convention-based approaches usually allow for duck-typing; with middleware, it means you can write PHP callables - usually closures - and just expect them to work.

Contract-based approaches use interfaces. I think you can see where this is going.

He starts off looking at some of the currently popular methods for creating middleware basic them off of either the PSR-7 standard or the proposed PSR-15 HTTP middleware, each with code examples to illustrate. The post then gets to the point with a look at anonymous class-based middleware and some of the advantages they provide. He refactors both a PSR-7 middleware and a closure-based middleware over to PSR-15 using this method.

tagged: middleware anonymous class psr7 psr15 closure tutorial

Link: https://mwop.net/blog/2017-03-30-anonymous-class-middleware.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/

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 1)
Mar 06, 2017 @ 11:12:04

On his site Mark Baker has posted the first part of a series of articles covering the use of closures and anonymous classes in testing and mocking. In this first part of the series he focuses on introducing some of the basics of the topics to be covered and what the closures/anonymous classes can replace.

Since their first introduction with PHP 5.3, Closures have proven an incredibly useful feature for writing simple callback code, making it cleaner and more intuitive. Anonymous Functions can be used inline for many of the array functions or assigned to a variable as a Lambda that can be referenced many times in different places in your code.

[...] But this isn’t an article about the differences between Anonymous and Lambda Functions and Closures [...] Instead, I want to take a look at binding Closures to objects as a first step to demonstrating an alternative approach to test mocking.

He goes on to talk about the mocking the PHPUnit already includes, other libraries that help with mocking/stubs but then pushing those off for the focus of the article - the use of the closures/anonymous classes. He gets into some details about how PHP handles closures internally and how to bind a closure to a class or object instance (via the bindTo function). He then attaches this to an object and shows how to create a "snooper" to work with an object, perform some processing and return some values from it.

tagged: closure anonymous function tutorial testing unittest phpunit snooper

Link: https://markbakeruk.net/2017/03/05/closures-anonymous-classes-test-mocking-1/

Matt Stauffer:
Defining console commands via closure in Laravel 5.3
Feb 17, 2017 @ 11:06:37

Matt Stauffer has posted the latest article in his "New Features in Laravel 5.3" series today. In this new tutorial Matt focuses on the creation of console commands - additional functionality you can add in to the pre-existing "artisan" command handling.

Before Laravel 5.3, defining an Artisan console command—something like php artisan sync:dates—required you to create a new class for that command and register it in the Console Kernel. This is fine, but sometimes it feels like overkill for what might end up just being a single line of functional code.

As of Laravel 5.3, you'll notice that there's a new method in the Console/Kernel.php file named commands(), and it loads a new file at routes/console.php. This new "console routes" file allows us to define Artisan console commands with a single Closure instead the prior "define a class then register it in the console Kernel" flow. Much faster, much easier.

In v5.3 you define commands using "routes" along with a simple description using fluent statements. He shows how to add a simple command, one with input and a more streamlined example pulling values directly from the "route" signature.

tagged: laravel console commands closure v53 version tutorial route closure

Link: https://mattstauffer.co/blog/defining-console-commands-via-closure-in-laravel-5-3

Matt Stauffer:
Defining console commands via closure in Laravel 5.3
Feb 17, 2017 @ 11:06:37

Matt Stauffer has posted the latest article in his "New Features in Laravel 5.3" series today. In this new tutorial Matt focuses on the creation of console commands - additional functionality you can add in to the pre-existing "artisan" command handling.

Before Laravel 5.3, defining an Artisan console command—something like php artisan sync:dates—required you to create a new class for that command and register it in the Console Kernel. This is fine, but sometimes it feels like overkill for what might end up just being a single line of functional code.

As of Laravel 5.3, you'll notice that there's a new method in the Console/Kernel.php file named commands(), and it loads a new file at routes/console.php. This new "console routes" file allows us to define Artisan console commands with a single Closure instead the prior "define a class then register it in the console Kernel" flow. Much faster, much easier.

In v5.3 you define commands using "routes" along with a simple description using fluent statements. He shows how to add a simple command, one with input and a more streamlined example pulling values directly from the "route" signature.

tagged: laravel console commands closure v53 version tutorial route closure

Link: https://mattstauffer.co/blog/defining-console-commands-via-closure-in-laravel-5-3

Dave Marshall:
Using Closures as PHPUnit After Hooks
Dec 26, 2016 @ 14:21:32

Dave Marshall has written up a post showing how you can use closures with PHPUnit to provide "after" hook functionality.

Not sure why I didn't start doing this sooner. We have a basic Feature toggle system that is maintained in the global scope to make it easily accessible to any part of the code. [...] I needed to force a particular feature on in a PHPUnit integration test, but in order to tidy up after myself, I would need to ensure that the test reset the Feature system after it had finished. There are a few ways of doing this.

The first of the three, using PHPUnit's own global state handling comes with its own set of problems. The second was to use a try/catch block in the test to ensure the state is reset and a third was to use the "tearDown" to reset everything accordingly. He ended up finding what he needed in the form of "runAfterHooks" handling in a trait, passing in the closure to be executed.

tagged: phpunit unittest closure hook tutorial trait

Link: http://davedevelopment.co.uk/2016/12/23/using-closures-as-phpunit-after-hooks.html

Joseph Silber:
The new Closure::fromCallable() in PHP 7.1
Jul 26, 2016 @ 10:20:47

In a new post to his site Joseph Silber looks at a new feature that will be coming with the next release in the PHP 7.x series - PHP 7.1 - the ability to convert a callable type into an actual Closure instance.

With PHP 5.5 going EOL earlier this week and the PHP 7.1 beta expected later this month, now sounds like a good time to look into a neat little feature coming in 7.1: easily converting any callable into a proper Closure using the new Closure::fromCallable() method.

He starts with a quick refresher on what closures/callables are in PHP (or an introduction for those not already familiar) including a simple example with the reject handling on a Laravel collection. He then modifies the example to try to pass in a base PHP function. This doesn't work directly (as it's not technically "callable" how it's expecting) so he wraps the is_float in a closure instead. This is a bit of a hassle and not as reusable so he updates it for PHP 7.1 and uses the Closure::fromCallable handling to make it automatically. He follows this with another example use case: calling a private method with the array of object/method name from inside the class.

tagged: closure callable fromcallable php7 example introduction

Link: https://josephsilber.com/posts/2016/07/13/closure-from-callable-in-php-7-1