collections icon indicating copy to clipboard operation
collections copied to clipboard

Get default value if target element not found

Open spam312sn opened this issue 5 years ago • 6 comments

Update get method with one more additional method parameter which will be used as default value if target element couldn't be found.

Example: Symfony ParameterBag

spam312sn avatar Jul 07 '19 14:07 spam312sn

personally i think $collection->get($id) ?? $default is more expressive, than $collection->get($id, $default)

someniatko avatar Nov 21 '19 08:11 someniatko

The $collection->get($id) ?? $default approach won't work if you need to store null in the collection however I'm not sure a lot of people are storing null in the collections.

malarzm avatar Nov 23 '19 11:11 malarzm

A change of the get() method API would break packages where collection is a dependency and still uses the variant without a default value argument. Projects are implementing the Collection interface and this would also affect Doctrine projects like ORM and the PersistentCollection. At the current time Packagist lists 628 packages that are dependents.

The influence and circumstances of such a change on maintenance compared to its benefit doesn't pay off IMHO.

SenseException avatar Nov 27 '19 22:11 SenseException

While the BC break is definitely to be avoided, we'll have to think about how to solve this in the future: there were numerous feature requests that would've been nice to implement but were skipped because of the BC implications.

alcaeus avatar Nov 28 '19 12:11 alcaeus

Since the get method returns null in case the value is not found (which serves as some kind of a default), wouldn't the following signature get($key, $default = null) prevent BC?

jwillp avatar Jun 02 '20 14:06 jwillp

@jwillp No, it will not. BC does not only concern interface usage, but also interface implementation. Changing method signature would mean each CollectionInterface implementor would need to support the second parameter.

someniatko avatar Jun 02 '20 17:06 someniatko