News Feed
Sections




News Archive
feed this:

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

Marco Pivetta:
Accessing private PHP class members without reflection
August 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.

0 comments voice your opinion now!
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
March 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.

0 comments voice your opinion now!
array closure callback example


Andrew Podner:
Closures, Lambdas, and Anonymous Functions
February 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.

0 comments voice your opinion now!
closure lambda anonymous function introduction


Vance Lucas:
Handling Exceptions in Gearman Tasks (Even Background Ones)
August 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.

0 comments voice your opinion now!
gearman exception handling try catch closure


BinaryTides.com:
Javascript style object literals in PHP
July 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.

0 comments voice your opinion now!
javascript object literal tutorial closure calluserfuncarray


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.
0 comments voice your opinion now!
ternary nested anonymous function closure compare


DevShed:
PHP Closures as View Helpers Lazy-Loading File Data
January 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.

0 comments voice your opinion now!
tutorial closure lazyload file serialize view helper


DevShed:
Using Closures as View Helpers
January 25, 2012 @ 09:50:38

New on DevShed today there's a tutorial looking at using one of the newer features of PHP, closures, as view helpers in a basic templating system.

In this two-part tutorial I'll be showing you, in a step-by-step fashion, how to use the goodies offered by closures in the implementation of an object-based, easily extendable template system. This system will allow you to embed anonymous functions easily into template files, and call them as typical view helpers, too.

He starts the process of creating the templating system by defining two interfaces, the View and DataHandler. Using these as a base, he creates an instance of the ViewInterface (a "View" class) that can set the template file to use, set values to be displayed and render the formatted output. Included is a basic template and how to use the View class to set values into it. The "render" method is called on the view and the HTML markup is produced. The closure comes in when they try to call a value "clientIp" that needs to do something more complicated than just having a string assigned to it.

0 comments voice your opinion now!
closure view helper template view interface


Davey Shafik's Blog:
The Closure Puzzle
January 16, 2012 @ 09:52:38

Davey Shafik has posted about an interesting find with closures in PHP revolving around an update to add "$this" access inside the closure.

However, it didn't stop there; there was also the addition of Closure::bind() and Closure->bindTo(). These methods are identical except one is a static method into which the closure is passed, the second an instance method on the closure itself. These methods both take two arguments (on top of the closure for the static version): $newthis and $newscope. What this means is that unlike the regular object model the concept of $this and lexical scope (what is in scope for the function with regards to private/protected methods inside objects) are completely separated.

He also mentions that you can change the "$this" to a different object (complex) or swapping out the object the closure is bound to while keeping "$this" the same (simpler). He mentions that it could be useful for unit testing but can have its drawbacks. He's included code to illustrate the breakage it can cause in the PHP OOP model (with an explanation).

0 comments voice your opinion now!
closure puzzle bindto bind oop object


Jake Smith's Blog:
Callback Filter Iterator in PHP 5.3/5.4
December 02, 2011 @ 08:44:34

Jake Smith has a new post to his blog today about a feature included in PHP's Standard PHP Library that you might have overlooked - the FilterIterator's callback functionality.

The Filter Iterator is probably my second favorite iterator, next to Directory Iterator. There are many great use cases for the Filter Iterator, and when you do filter the original data is left untouched. A Filter Iterator is really simple to use, create a class that extends FilterIterator and adjust the accept method to meet your criteria. This is great and all, but having the ability to create filter iterators on the fly, ones that won't be used application wide, without having to create a class is even better.

He includes a bit of code defining a FilterCallbackIterator class with a "callback" parameter passed into the constructor (in his case, a closure). Also included is some sample code of it in use - handling an array (well, ArrayIterator) with a simple true/false check on the current array value. You can find out more about this functionality in the PHP manual.

0 comments voice your opinion now!
callback filter iterator spl tutorial closure



Community Events





Don't see your event here?
Let us know!


language list release community threedevsandamaybe framework configure install introduction developer unittest interview podcast testing code opinion laravel refactor series symfony2

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework