6 * The Collection classes inheriting from this abstract class are meant to represent a list of database record.
7 * The associated model class has to be provided in the child classes.
9 * Collections can be used with foreach(), accessed like an array and counted.
11 abstract class BaseCollection extends \ArrayIterator
14 * This property is used with paginated results to hold the total number of items satisfying the paginated request.
17 protected $totalCount = 0;
20 * @param BaseModel[] $models
21 * @param int|null $totalCount
23 public function __construct(array $models = [], int $totalCount = null)
25 parent::__construct($models);
27 $this->models = $models;
28 $this->totalCount = $totalCount ?? count($models);
34 public function offsetSet($offset, $value)
36 if (is_null($offset)) {
40 parent::offsetSet($offset, $value);
46 public function offsetUnset($offset)
48 if ($this->offsetExists($offset)) {
52 parent::offsetUnset($offset);
58 public function getTotalCount()
60 return $this->totalCount;
64 * Return the values from a single field in the collection
66 * @param string $column
67 * @param int|null $index_key
71 public function column($column, $index_key = null)
73 return array_column($this->getArrayCopy(), $column, $index_key);
77 * Apply a callback function on all elements in the collection and returns a new collection with the updated elements
79 * @param callable $callback
80 * @return BaseCollection
83 public function map(callable $callback)
85 return new static(array_map($callback, $this->getArrayCopy()), $this->getTotalCount());
89 * Filters the collection based on a callback that returns a boolean whether the current item should be kept.
91 * @param callable|null $callback
93 * @return BaseCollection
96 public function filter(callable $callback = null, int $flag = 0)
98 return new static(array_filter($this->getArrayCopy(), $callback, $flag));