tags:

views:

76

answers:

2

I want to write a static method in a class to generically sort an array of objects.

I am thinking of somthing along the lines of:

class GenUtils {
  const ASCENDING = 1;
  const DESCENDING = 2;

  protected static alphaSort($value1, $value2, $sort_type=self::DESCENDING){
     $retval = strcasecmp($value1, $value2);
     return ($sort_type == self::DESCENDING) ? $retval : (-1*$retval);
  }

  protected static numericSort($value1, $value2, $sort_type=self::DESCENDING){
    return  $value1 < $value2;
  }

  // Assumption: array is non-empty and homogeneous
  public doSort(array& $object_array, $method_name, $sort_type=self::DESCENDING) {
        if(!empty($object_array) && method_exists($object_array[0],$method_name)) {
          $element = $object_array[0];
          $value = $element->$method_name();
          if(is_string($value)){
            //do string sort (possibly using usort)
          }
          elseif(is_number($value)){
            //do numeric sort (possibly using usort)
          }
        }
  }
}

This is just a quick brain dump -perharps someone can fill in the missing pieces, or suggest a better way of doing this?

[Edit] Just to clarify, the objects to be sorted (in the array), have methods which return either a string (e.g. getName()) or a numeric value (e.g. getId())

A typical usecase code snippet would therefore be somethimng like this:

GenUtils::doSort($objects,'getName'); // This will do an alphabetic DESC sort using the getName() method

GenUtils::doSort($objects, 'getId', GenUtils::ASCENDING); // This will do a numeric ASC sort using the getId() method
+1  A: 

The use cases (numeric and string) in your example are already built in to PHP - Check out the sort function. I would use the built-in function unless I had more specific needs.

Håvard S
And how do you tell the sort function which method it needs to call to get the actual value?
poke
Thats partly what I'm asking... I can "hack it" to get it to do what I want, but I want to know if there is a more natural or elegant solution to it - afterall, PHP is not my "native" language, so I'm sure there are some in here who can suggest a more elegant or PHP-like approach. The doSort() method takes the name of the method to be called on the array element (objects). The called method returns either a string or a number (for now), so once the required comparison function is determined, its simply a case of calling usort with the approp. callback (I think I just answered my own question!)
Stick it to THE MAN
+1  A: 

Use usort and define your own comparison function to work with your objects.

poke