Functional Programming in PHP

For the last half a year I have been coding in Scala and today I had to switch back to PHP to add some functionality to an old service. The interesting part was that it was coming more naturally to me to use filter and map to do my job instead of using foreach. Well .. here is what came out:


$keywords = array_filter( explode(" ",$keyword), function($x) { return !empty($x); } );
$keywordsQuery = implode( " AND ", array_map ( function($x) { return "body LIKE '%$x%'"; }, $keywords) );

This was the first time I was using array_filter and array_map and anonymous functions so I was very excited while writing it but the result isn’t the most readable. Also it wasn’t so easy to write it cause I had to go to the PHP website to check in which order do the arguments go (first the callback or the array?), which is something you don’t need to check when coding in a more object-oriented way. Also I noticed that PHP’s anonymous functions have a similar ugliness with Javascript. You have to write the whole word “function” which takes quite some space and makes inline anonymous functions very verbose & hard to read.

Anyway. Luckily I wont have to write too much code in PHP for this new feature and I hope there wont be many more things to write in PHP. I’m not saying that the there is something wrong with the language. I’m just saying it’s hard to go back from Scala to PHP.

So .. that’s all I wanted to share with you today. Below is the code of how I would do it in Scala (didn’t run it but more or less it should work!).


keywords = keyword.split(" ").filter(_.nonEmpty).map(x => "body LIKE '%" + x + "%'").mkString(" AND ")

Advertisements

One thought on “Functional Programming in PHP

  1. Moving from PHP to Scala, and also noticed that the functional code in PHP is not so pretty…

    // using closure cache style to get cache stored value (still have to bind closure params explicitly)
    $user = $cache->getOrElse(‘user’, function($userRepository, $userId) {
    return $userRepository->get($userId);
    });

    // equivalent in scala:
    val user = cache.getOrElse(‘user’, userRepository.get(userId));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s