PHP code example of goksagun / collection

1. Go to this page and download the library: Download goksagun/collection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

goksagun / collection example snippets




namespace Acme;

class Product
{
    public function __construct (
        private string $name,
        private float $price
    ) {}

    public function getName(): string
    {
        return $this->name;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

}



namespace Acme;

use Acme\Product;
use Goksagun\Collection\Collection;

/**
 * @implements Collection<Product>
 */
final class ProductCollection extends Collection
{

    public function __construct(Product ...$items)
    {
        parent::__construct(...$items);
    }

}



namespace Acme;

use Acme\Product;
use Acme\ProductCollection;

$collection = new ProductCollection(
    new Product('Product 1', 100.99),
    new Product('Product 2', 200.99),
    new Product('Product 3', 300.99),
);

$total = $collection
    ->map(function (Product $product) {
        return new Product($product->getName(), $product->getPrice() * 1.18);
    })
    ->each(function (\Goksagun\Collection\Test\Fixtures\Product $product, int $index) {
        echo "Product {$index}: {$product->getName()} - {$product->getPrice()}\n";
    })
    ->filter(function (Product $product) {
        return $product->getPrice() > 300;
    })
    ->pluck('price')
    ->reduce(function (float $total, float $price) {
        return $total + $price;
    }, 0);

echo "Total: {$total}\n";

// Product 0: Product 1 - 119.1682
// Product 1: Product 2 - 237.1682
// Product 2: Product 3 - 355.1682
// Product 0: Product 3 - 355.1682
// Total: 355.1682