Functional programming in PHP

With the introduction of lambda (or anonymous) functions in PHP 5.3 it is now possible to introduce some nice features from the functional programming paradigm.

Higher order function

When a method (or function) accepts another function as parameter this function is called a higher order function. The following already worked in PHP < 5.3 and is a simple implementation of functional programming with callable variables.

$data = array(10,2,6,4);
function cmp($a, $b) {
    if ($a == $b) return 0;
    return $a < $b ? -1 : 1;
}
usort($data, "cmp");

Continue reading Functional programming in PHP

Zend_Date caching

What started with a simple month subtraction function ends with a total nightmare on performance. Using Zend_Date is smart because it can correctly calculate the previous month taking into account months like february and leap years.

public static function previousMonth($year, $month)
{
   $date = new Zend_Date();
   $date->setYear($year);
   $date->setMonth($month);
   $date->sub(1, Zend_Date::MONTH);

   return = array(
      self::$date->get(Zend_Date::YEAR), 
      self::$date->get(Zend_Date::MONTH)
   );
}

Continue reading Zend_Date caching

MongoDB map/reduce

Map/reduce in MongoDB is quite difficult the get familiar with. In this post I’ll try to explain the basics with a real-life example.

Map/reduce can be used by calling this function with the following arguments

db.collection.mapReduce(
     mapFunction,
     reduceFunction,
     {
        out: collection,
        query: document,
        finalize: function
     }
)
  • mapFunction, javascript function that will be explained below
  • reduceFunction, javascript function that will be explained below
  • out: name of the collection where the reduced data should be written to
  • query: query of the data where to apply the map/reduce on
  • finalize: function that is applied only once on the reduced data

Continue reading MongoDB map/reduce