php-fu

Functors for your single-parameter callback blues

When using PHP functions such as array_map, usort or preg_replace_callback, you are forced to pass in a single-parameter callback function, making it impossible to send additional context information to the callback. But it ain't necessarily so.

Function objects, aka Functors, are here to help.

Dealing with deep arrays in PHP

Drupal code is heavily array-based, and it utilizes array structures that can be many levels deep. Here are a couple of complementary functions to query and manipulate such arrays:

<?php /** * Search for a key in an array, returning a path to the entry. * * @param $needle * A key to look for. * @param $haystack * A keyed array. * @param $forbidden * A list of keys to ignore. * @param $path * The intermediate path.

A function to simplify SQL queries

Every time I have to write one of these SQL query loops, I feel unclean:

<?php
 
// Oh no, not another db_query loop!
 
$resource = db_query("SELECT nid, title FROM {node}");
  while (
$row = db_fetch_array($resource)) {
   
$result[$row['nid']] = $row['title'];
  }
 
// Get on with your normal life here...
 
do_something_useful($result);
?>

So I decided to create a function that encapsulates the common scenarios for SQL queries.

The Automatic Resource Destructor pattern

Originally published at OpenCraft.

What happens if you need to open a file with fopen, but find that your function can exit at multiple points? It is tedious and error-prone to call fclose at each exit point. Alternatively, you could re-structure your code to only exit at the bottom, thereby calling fclose only once, but you would end up with many nested blocks that hamper readibility and are generally considered bad programming style.

A technique I like to use in those cases is the Automatic Resource Destructor.

Syndicate content