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->totalCount = $totalCount ?? count($models);
33 public function offsetSet($offset, $value)
35 if (is_null($offset)) {
39 parent::offsetSet($offset, $value);
45 public function offsetUnset($offset)
47 if ($this->offsetExists($offset)) {
51 parent::offsetUnset($offset);
57 public function getTotalCount()
59 return $this->totalCount;
63 * Return the values from a single field in the collection
65 * @param string $column
66 * @param int|null $index_key
70 public function column($column, $index_key = null)
72 return array_column($this->getArrayCopy(), $column, $index_key);
76 * Apply a callback function on all elements in the collection and returns a new collection with the updated elements
78 * @param callable $callback
79 * @return BaseCollection
82 public function map(callable $callback)
84 return new static(array_map($callback, $this->getArrayCopy()), $this->getTotalCount());
88 * Filters the collection based on a callback that returns a boolean whether the current item should be kept.
90 * @param callable|null $callback
92 * @return BaseCollection
95 public function filter(callable $callback = null, int $flag = 0)
97 return new static(array_filter($this->getArrayCopy(), $callback, $flag));