collections
collections copied to clipboard
Get default value if target element not found
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
personally i think $collection->get($id) ?? $default
is more expressive, than $collection->get($id, $default)
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.
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.
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.
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 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.