[Proposal] Add functionality to Collection class
After some thought and discussion I think the Collection class is awesome and I'd like to use it more in my app code, but could do with some added functionality - mostly around associative data. My thoughts so far are:
Note: using static notation for ease of display
Check for existence of key in the collection:
Collection::has($key)
Return data for the given key:
Collection::get($key, 'default')
Remove given key from array, if it exists:
Collection::remove($key)
Add a value with a given key - probably just syntactic sugar alias of Collection::offsetSet():
Collection::add($key, $value)
Collection::push($value) // Alias: Collection::add(null, $value)
Finally, a magic __get() method, which could be used to access array values as if they were object attributes:
public function __get($key)
{
if (isset($this[$key]))
{
return $this[$key];
}
}
A lot of these functions can make use of the array helper functions defined in the core helpers.php file, allowing for dot notation access for nested data.
I can see this stuff being useful.
Since you mentioned the array helpers it might be useful to make use of array_set() in the offsetSet() and offsetGet() methods to allow for nested keys. Of course, if you implement a Collection::get() then these methods should just use that instead (and it should use the array helper functions).
I did think about updating those functions as well, makes sense to me!
Done.