Collections - ApinePHP/legacy-framework GitHub Wiki
The Collection is an object oriented approach to array. It removes the need to remember many dozens of methods and complex array syntax, and is travesable like an array. It is extensively used for it's ease of use with Entity Models.
The class is named Collection and is part of the Core module.
use Apine\Core\Collection;
use Apine\Entity\BasicEntity;
...
$item_str = "Hello World!";
$item_int = 404;
$item_bool = false;
$item_array = array(0, 2, 4, 6, ,8);
$item_entity = new BasicEntity("apine_users", 5);
$liste = new Collection();
$liste->add_item($item_str); // Automatic Index Positionning, Current : 0
$liste->add_item($item_int); // 1
$liste->add_item($item_bool, 'bool'); // Custom Indexing. Index 'bool'
$index_array = $liste->add_item($item_array); // add_item returns the new index. Returns 2
$intex_entity = $liste->add_item($item_entity, 'entity'); // The same goes for custom indexes
$str_item = $liste->get_item(0); // Return element at index 0
$no_item = $liste->get_item(3); // Returns false index not found
$bool_item = $liste->get_item('bool'); // The same goes for custom indexes
$liste->remove_item('bool'); // Returns true if the item is removed. If not, false.
$length = $liste->length(); // Returns the number of items in the collection
foreach ($liste as $index => $item) {
// Traversing the collection like an array
}
It is possible to iterate through the collection like you would with a regular array. Using a foreach loop, there is no differences between a regular array
foreach ($liste as $index => $item) {
// Traversing collection like an array
}
However, it is possible to use a for loop but it implies you only use automatic indexing.
for ($i = 0; $i < $liste->length(); $i++) {
$item = $liste->get_item($i);
// Traversing collection almost like an array
}
Add an item to the collection
Remove an item from the collection
Fetch an item from the collection
Fetch every item in the collection
Fetch the first item in the collection
Fetch the last item in the collection
Reverse item order in the collection
Sort item by value in the collection
Get an array of every item keys in the collection
Count all items in the collection
Verify if key exists in the collection
Verify if value exists in the collection
Return external iterator for the collection. Implementation from the IteratorAggregate interface.