SPL iterators with closure context switching

Some time ago I redi­sco­ve­red PHP SPL library. After reading Joshua Thijssen’s Maste­ring the SPL Library I found out that some­ti­mes I was reinven­ting the wheel in my code, sorry (employ­ers and custo­mers). Itera­tors are one of the SPL library compo­nents. To add more spice to code I’ll show some kind of Java­Script magic using closures.

Simplest and best itera­tor definition:

Itera­tors are PHP’s way of dealing with abstrac­ting away the traver­sal logic from the busi­ness logic. This, in one sentence, sums up what an itera­tor is. [J. Thijs­sen : Maste­ring…, p. 68]

My goal for today is to show you how to use Itera­to­rAg­gre­gate with Call­back­Fil­te­rI­te­ra­tors to filter out files not meeting our requ­ire­ments.

Feel free to use this class in your own projects.


Function overloading in JavaScript

I won’t talk about PHP today. Sorry PHPers. If you do some fron­tend job, you won’t be disap­po­in­ted. I’m assu­ming you know some basic Java­Script stuff like closu­res, proto­ty­ping and context swit­ching, because I’m going to do some cheating.

Our goal for today is to force Java­Script to invoke diffe­rent func­tions accor­ding to diffe­rent argu­ments number. To further compli­cate all of this, we’ll work on proto­ty­pes and check if over­lo­ading works on inhe­ri­ted objects.

I’ll use Coffe­eScript since it has nice, conden­sed syntax. You don’t need to write much JS boiler­plate like semi­co­lons and braces, what leads to about 30% less code in CS <-> JS compa­ri­son. Always remem­ber: Coffe­eScript is just Java­Script and you can simple paste it in Try Coffe­eScript’s section to see the JS compi­led result. Don’t worry, i’ll provide some hints in sensi­tive places.

Most impor­tant things for today are:

  • you can always check how many argu­ments func­tion has in its decla­ra­tion using length property,
  • you can always check how many argu­ments func­tion was invo­ked with by using arguments.length property.

A few ending thoughts:

  • augmen­ting methods have some perfor­mance penalty,
  • you’ll proba­bly compli­cate stuff when use over­lo­ading too much,
  • if you truly need that solu­tion in JS, you’re doing some­thing wrong :-)

Using streams in multi process environment

Today is the last instal­l­ment about PHP stre­ams. This time we will borrow some images from GitHub octo­dex using remote stre­ams and stream copy­ing. To add some spice, we’re going to use PHP in paral­lel proces­sing. If you thought PHP is single process srcrip­ting langu­age, I will ruin your world, sorry ;-)

Of course in real world projects there is always a trade off between time and reso­ur­ces. Forking process is CPU expen­sive work for server. We’re assu­ming we have plenty of CPU cycles and RAM, but short on time. Take a look on code below:

It took 5 secs to fetch 127 images. The same thing run in single fore­ach loop takes about 2 minutes…