(Lazy) Typed Collections #47373
Unanswered
henzeb
asked this question in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
PHP does not support generics. This has bugged me from the start. Returning a single User is fine, but what about an array or User objects?
Now, there are 2 other packages, one abandoned, and the other quite limited in my opinion. It doesn't support lazy collections for example. So I decided to make a new, better one.
Just install https://packagist.org/packages/henzeb/laravel-typed-collection
A typed collection can be predefined or created from an existing collection object. Let's see what a typical predefined typed collection look like:
Want it to be lazy? simply replace
TypedCollection;
withLazyTypedCollection;
:As you noticed, we can specify an array. Yes, the irony. But this one is validated. Throw anything in there that isn't supposed to be there and
boom
. With the array, you can have a union type like behavior:Whenever something is added in the Collection the type of the new item is validated. In a lazy collection this happens when yielded. It also doesn't lose the type check when piped through a method like
map
orfilter
.It's not only possible to pass class names and (scalar) types, it's also possible to create your own generic type if for example your type needs to be JSON or Uuid.
This way you can be sure that a method returns a list of items you actually want, and it makes the code more readable to your developers.
Beta Was this translation helpful? Give feedback.
All reactions