Inspired by a book I picked up over the weekend (Advanced PHP Programming), I created a Collection class to help perform operations on a group of CActiveRecord objects.
Example usage:
$customers = new Collection(Customer::model()->findAll());
$customers->set('promocode', 'nerdist');
if ($customers->reduce(true)->call('save')) {
// All changes made successfully
} else {
// At least one error. Rollback / do post-processing
}
The following methods are available:
-
call(): Call a method for every object in the collection.
-
set(): Set an attribute’s value for every object in the collection
-
get(): Get an attribute’s value for every object in the collection
-
addItem(): Add a CActiveRecord object to the collection
-
removeItem(): Remove an object from the Collection
-
getItem(): Get an object from the Collection using a key
The class implements the Iterator interface (so it’s foreach’able) and also supports very basic internal versus external key manipulations. The key part could use some work to make it more intuitive as well as to improve interfacing with CActiveRecord.
Is there any interest in continuing the development of this class? It seems like it might be useful when performing batch inserts/updates or any operation that needs to be transactional, but for which a transaction is not supported. (Which could be handled by backing up the Collection before performing the operation, then restoring it if the operation failed.)
Would love to hear what the community thinks. (Especially if the answer is “don’t waste your time” )
4291