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

Julien Pauli:
PHP closures
Jul 10, 2015 @ 10:54:29

Julien Pauli has posted a look at PHP's closures and how they're actually handled internal to the language.

Back in 2009, when PHP 5.3 got released, a new feature (among many others) were introduced : anonymous functions (also called lambdas or closures). The feature was very expected, as closures have proved their utility through several other languages, particularly javascript that web developers master. [...] Let's see together how Closures have been added to PHP, as usual by turning to the truth : the PHP source code.

He starts at the beginning (a good place to start) and talks about the work that needed to be done on the internals before closures could even be introduced. He walks through the changes made to object handling to make them "callable" and the addition of the "zend_closure" object type. He then gets to the part where "the magic happens" and shows how the userland closure is translated and executed. He ends the post with a look at two other topics: scoping with "$this" and the special handling that was needed for reflection and direct calls to "__invoke".

tagged: closure language functionality object callable scope reflection invoke

Link: http://jpauli.github.io/2015/07/08/php-closures.html

Barry vd. Heuvel:
Using StackPHP middleware in Laravel5
Feb 19, 2015 @ 09:49:24

Barry vd. Heuvel has a new post sharing a method he's found for using StackPHP middleware with Laravel 5 and provides a library of his own to make moving between the middleware types easier.

In version 4.1, Laravel introduced compatibility with StackPHP middleware. [...] In Laravel 5, a lot of things changed. And with those changes, Laravel also removed the support for StackPHP middleware and introduced its own middleware contract.

As the two types of middleware have interfaces that slightly conflict, he shows how to convert from one to the other (a relatively simple change). He then shows how to use the middleware in a Laravel 5 application, but brings up a "chicken and the egg" situation where a wrapper for the HttpKernelInterface is needed for correct injection. To that end he created two simple wrappers, the ClosureMiddleware and ClosureHttpKernel handlers that can be used to simplify this middleware translation.

tagged: stackphp middleware laravel5 convert wrapper closure

Link: http://barryvdh.nl/laravel/2015/02/18/using-stackphp-middleware-in-laravel-5/

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/

Marco Pivetta:
Accessing private PHP class members without reflection
Aug 15, 2013 @ 12:53:55

Marco Pivetta has posted about an interesting trick you can do with closures in PHP related to accessing private properties inside classes.

A couple of weeks ago I was working on a very tricky issue on ProxyManager. The problem is simple: instantiating ReflectionClass or ReflectionProperty is slow, and by slow, I mean really slow! The reason for this research is that I'm trying to optimize a "hydrator" to work with larger data-sets by still keeping a low initialization overhead. PHP 5.4 comes with a new API for Closures, which is Closure#bind(). Closure#bind() basically allows you to get an instance of a closure with the scope of a given object or class. Neat! That's basically like adding APIs to existing objects! Let's break some OOP encapsulation to fit our needs.

He shows how to use this "bind" feature to reach into an object, in this case a "Kitchen", and extract the value of an internal, private property. He also talks some about the performance of this method versus the more typical use of Reflection. He includes two other quick examples too - accessing the same private properties by reference and an abstracted "property reader" closure that uses the bind trick on any object.

tagged: private method reflection closure bind alternative performance

Link: http://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection

Setfive.com:
PHP: Some thoughts on using array_* with closures
Mar 19, 2013 @ 10:36:22

On the Setfive site there's a recent post from Ashish Datta about some thoughts around array functions and closures for callback methods.

The other day, I was hacking away on the PHP backend for the “Startup Institute” visualization and I realized it was going to need a good deal of array manipulation. Figuring it was as good a time as any, I decided to try and leverage PHP 5.3+ new closures along with the array_* functions to manipulate the arrays. I’m not well versed with functional programming but I’ve used Underscore.js’s array/collection functions so this is mostly in comparison to that.

He gives a sample data set he's pulling from - basic user data - and goes through a few different actions that can be taken on the data (with code examples for each): sorting, mapping and filtering. He shows the use of closures as the callback methods instead of defining them separately and passing in their names.

tagged: array closure callback example

Link:

Andrew Podner:
Closures, Lambdas, and Anonymous Functions
Feb 21, 2013 @ 13:02:13

Andrew Podner has posted an introduction to a concept in PHP that may not be easy to immediately grasp for someone relatively new to the language - the idea of lambdas and closures.

Beginning with PHP 5.3, the anonymous function, became available to developers as a means of improving flexibility and increasing the number of tools at our fingertips to build powerful PHP applications. What I have been seeing a lot of as I read through documentation is more frequent use of terms like lambda, closure, or anonymous function, and sometime the terms are often used interchangeably, so let’s take a deeper look into what all of these things are and what differences, if any, there are between them.

The post looks at lambdas first, defining them as "functions without names" that can be assigned to objects or called inline when needed. Next is closures, and it's noted that, in PHP, there's really not much difference. They both also allow for use of the "use" statement to import values into the function's local scope. He mentions the "$this" update that came in PHP 5.4 and includes some arguments against their use too.

tagged: closure lambda anonymous function introduction

Link:

Vance Lucas:
Handling Exceptions in Gearman Tasks (Even Background Ones)
Aug 03, 2012 @ 08:28:25

Vance Lucas has a quick new post to his site showing you how to handle exceptions in Gearman tasks so that they can be logged correctly as a failure.

I recently had some issues with Gearman tasks throwing exceptions and killing the whole Gearman daemon. This made it nearly impossible to trace errors back to their origin, because the logged exception stack trace didn’t provide much useful information, because it just logged where it failed in Gearman. [...] The only other place to add code that will catch exceptions for all jobs run is in the GearmanWorker::addFunction method.

To solve the issue, he ends up passing in a closure that takes in the $task and wraps its execution in a try/catch to handle the exception correctly. This is then thrown to a custom exception handler and logged for future diagnosis.

tagged: gearman exception handling try catch closure

Link:

BinaryTides.com:
Javascript style object literals in PHP
Jul 25, 2012 @ 10:44:25

On the BinaryTides.com site there's a recent post for those familiar with Javascript and wanting to have the same kind of object-style literals in PHP.

As similar thing [to Javascript object literals] can be done in PHP using anonymous functions (since 5.3) [...] Since version 5.3 Php added support for closures and that feature has been used above to create javascript style object literals. The use(&$a) expression makes the variable $a available inside the function happy.

Code snippets are included showing how to create these objects via the use of closures and a little trickery with call_user_func_array and __call to make assigning properties easier.

tagged: javascript object literal tutorial closure calluserfuncarray

Link:

PHP Tip-a-Day:
PHP Tutorial: Convoluted Code - Combining Ternary Operators and Anonymous Functions
May 30, 2012 @ 10:09:40

On the PHP Tip-a-Day site Greg Bulmash shares a bit of "convoluted code" that could potentially cause confusion in the future maintenance of your application - combining ternary with anonymous functions.

Following on yesterday's post about chaining if statements without brackets on a single line, I tried to explore other ways to perform this "test if the variable is set, then do a comparison if it is" logic. I created one of the most convoluted lines of code I've ever written. It's no SQL join that spans 5 whiteboards, but it's pretty unreadable.

His example uses not just one ternary comparison, but nested ones with the anonymous function as the first condition. He points out that, if you're not careful with this method and make both sides anonymous functions, you could be in for a "cannot be converted to string" error on the closure side.

I'm sure there might be a very good reason to put two anonymous functions in a ternary operator, but I can't think of one at the moment. It's a fairly ugly proposition.
tagged: ternary nested anonymous function closure compare

Link:

DevShed:
PHP Closures as View Helpers: Lazy-Loading File Data
Jan 30, 2012 @ 13:08:28

In the second part of their look at using closures in PHP as view helpers, DevShed improves upon their original code by adding some additional classes and using them in the closures.

The best way to show you how using anonymous functions can help you to develop more efficient OO applications is with some functional, hands-on examples. With this idea in mind, in the installment that preceded this one, I implemented an extendable template system. This system could spawn view objects and render the template files associated with these objects.

In this second part of the (two-part) series they include "Serializer" and "FileHandler" classes and show how to use them inside of the closures to lazy-load in data from an external file and work with it as serialized content.

tagged: tutorial closure lazyload file serialize view helper

Link: