Collection

Collections act as both arrays and iterators, and restrict all items within to be that of a specific class. You may create a new collection using the opus collection CLI command, such as:

apex opus collection <FILENAME> --item-class [FILENAME_OF_ITEM_CLASS]

apex opus collection MyShop/ProductCollection --item-class Myshop/Models/Product

Using the above example, a new file will be created at /src/MyShop/ProductCollection.php, which acts as an array that restricts its items to only instances of the App\MyShop\Models\Product class. All normal array functions are available, including iterating over the items within the array with a foreach or while loop.

Upon creating a new instance of the class, you may pass the $items argument which must be a one-dimentional array of objects of the item-class you defined for the collection. For example:

use App\MyShop\Models\Product;
use App\Myshop\ProductCollection;

$products = [
    new Product(15),
    new Product(82),
    new Product(528)
];

$col = new ProductCollection(
    items: $products
);

foreach ($col as $prod) {
    echo "ID: $prod->id\n";
}