Skip to content
Youmy001 edited this page Feb 4, 2018 · 3 revisions

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.

Basic Use Example

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
}

Traversing the Collection

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
}

Methods

add_item(mixed $a_item [, string $a_key = null]) : mixed

Add an item to the collection

remove_item(string $a_key) : boolean

Remove an item from the collection

get_item(string $a_key) : mixed

Fetch an item from the collection

get_all() : mixed[]

Fetch every item in the collection

get_first() : mixed

Fetch the first item in the collection

get_last() : mixed

Fetch the last item in the collection

reverse() : boolean

Reverse item order in the collection

ksort() : boolean

Sort item by value in the collection

keys() : string[]

Get an array of every item keys in the collection

length() : integer

Count all items in the collection

key_exists(string $a_key) : boolean

Verify if key exists in the collection

value_exists(mixed $a_value) : boolean

Verify if value exists in the collection

get_iterator() : CollectionIterator

Return external iterator for the collection. Implementation from the IteratorAggregate interface.

Clone this wiki locally