How can PHP developers leverage object methods as callbacks in sorting functions to create a chain of responsibility for sorting complex arrays?
When sorting complex arrays in PHP, developers can leverage object methods as callbacks in sorting functions to create a chain of responsibility. This allows for more flexibility and customization in the sorting process, as different sorting criteria can be encapsulated in separate methods of an object. By chaining these methods together, developers can create a dynamic and reusable sorting mechanism for complex arrays.
class Sorter {
private $callbacks = [];
public function addSortCallback(callable $callback) {
$this->callbacks[] = $callback;
}
public function sortArray(array $array) {
usort($array, function($a, $b) {
foreach ($this->callbacks as $callback) {
$result = $callback($a, $b);
if ($result !== 0) {
return $result;
}
}
return 0;
});
return $array;
}
}
// Example usage
$sorter = new Sorter();
$sorter->addSortCallback(function($a, $b) {
return $a['name'] <=> $b['name'];
});
$sorter->addSortCallback(function($a, $b) {
return $a['age'] <=> $b['age'];
});
$data = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35]
];
$sortedData = $sorter->sortArray($data);
print_r($sortedData);