Answer the question
In order to leave comments, you need to log in
How to implement your abstract collection class?
Please help me to implement abstract collection class.
I would like to write my bike in order to fully understand how it should work, etc.
This class should solve problems with method return typing.
How I imagine it:
class PostCollection extends BaseCollection {
# Устанавливаю тип коллекции,
# при попытке добавить в коллекцию другой тип - выбрасываем исключение
protected static $collectionType = PostItem::class;
}
class PostItem {
//...
}
class Posts {
public function getAllPost() : PostCollection { ... }
}
Answer the question
In order to leave comments, you need to log in
The collection is just a pack. An array with digital keys. There are two types I named for myself - an array and a list.
Array - the keys are strictly numeric and strictly in order.
The list - the keys are strictly numeric but may be out of order and some of them may be missing
Checks in the end - they take the keys and oddly compare until they find the first difference. In the second case - until they find the string key. If you need to check the type, then each element in the same handicap is run through the callable definition. Apparently, in order not to drive away - for some reason they write these collections and set the type explicitly, in the class name. Then collective farms so that another type cannot be abandoned, and in general the PLO for the sake of the PLO is brought down.
All other attempts to shove the logic for working with a specific pack into the pack itself will inevitably lead to the removal of code and the creation of a service that can work on the pack. That is, over the array.
Why collections in Laravel? Because they are tired of passing by reference, probably, and writing methods for working on arrays. Maybe they couldn't figure it out. Maybe they got bored. But under the hood, this thing of theirs is spamming collections, so it's scary to think. $collection->merge() - we seem to be working with objects, which means it should be added to our collection. But instead, it creates a second collection and removes the first one to behave as it would with two arrays.
Here in Laravel it turns out with this game - they began to use objects, and then try to implement the behavior in the old fashioned way, as in arrays. And for what they now have this collection, except for checking that it is of such and such a type - it is not clear.
And this check itself is generally needed in one or two places in the entire program. The coolest thing is that you can put a model of another type into a collection of a certain type on the chest and everything will work. I mean, they didn't even use it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question