framework icon indicating copy to clipboard operation
framework copied to clipboard

[Proposal] Add functionality to Collection class

Open DanSmith70 opened this issue 13 years ago • 3 comments

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.

DanSmith70 avatar Apr 15 '13 10:04 DanSmith70

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).

jasonlewis avatar Apr 15 '13 10:04 jasonlewis

I did think about updating those functions as well, makes sense to me!

DanSmith70 avatar Apr 15 '13 10:04 DanSmith70

Done.

taylorotwell avatar Apr 17 '13 04:04 taylorotwell