Search code examples
phpmodel-view-controllerdatamapperredbeanarrayobject

Using PHP's ArrayObject to implement a collection of model objects


I am developing a "fat model" for my open-source project, and I am working on the layer that will sit between the ORM (RedBeanPHP) and the controller.

I will have a User class, and probably a UserFactory/UserMapper class that can construct User objects, as well as perform meta-actions like usernameExists, etc.

A number of other SO questions/blog posts have pointed out that if I need to retrieve a collection of User objects, it would be inefficient to have my UserMapper class iterate through through the result set and build n User objects.

My idea then, is to create a UserCollection class which implements PHP's ArrayObject class. UserMapper would be able to create a UserCollection that stores the raw result set internally, as a multidimensional array. I could then implement ArrayObject's iterator functions, [], etc to construct the corresponding User objects on demand.

Is this a smart way to do it? What do I need to consider before taking this approach?


Solution

  • It would appear that this is exactly how Laravel's ORM, Eloquent, does it:

    class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable {
    
    ...
    
    public function fetch($key)
    {
    return new static(array_fetch($this->items, $key));
    }
    
    }
    

    If the most popular PHP framework is doing it that way, I'd say it's a pretty good endorsement.