PHP code example of rkulik / fractal

1. Go to this page and download the library: Download rkulik/fractal 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/ */

    

rkulik / fractal example snippets

 php


= new \Rkulik\Fractal\Fractal(new \League\Fractal\Manager());

$product = [
    'id' => '123',
    'name' => 'T-shirt',
    'price' => '1290',
    'brand_name' => 'Nike',
    'gender' => 'm',
];

$transformer = function (array $product): array {
    return [
        'id' => (int)$product['id'],
        'name' => $product['name'],
        'price' => (int)$product['price'],
        'brand' => $product['brand_name'],
        'gender' => $product['gender'] === 'm' ? 'male' : 'female',
    ];
};

$item = $fractal->item($product, $transformer)->toArray();
 php


nsformer extends \League\Fractal\TransformerAbstract {
    public function transform(array $product): array
    {
        return [
            'id' => (int)$product['id'],
            'name' => $product['name'],
            'price' => (int)$product['price'],
            'brand' => $product['brand_name'],
            'gender' => $product['gender'] === 'm' ? 'male' : 'female',
        ];
    }
}

$fractal = new \Rkulik\Fractal\Fractal(new \League\Fractal\Manager());

$product = [
    'id' => '123',
    'name' => 'T-shirt',
    'price' => '1290',
    'brand_name' => 'Nike',
    'gender' => 'm',
];

$item = $fractal->item($product, new Transformer())->toArray();
 php


= new \Rkulik\Fractal\Fractal(new \League\Fractal\Manager());

$products = [
    [
        'id' => '123',
        'name' => 'T-shirt',
        'price' => '1290',
        'brand_name' => 'Nike',
        'gender' => 'm',
    ],
    [
        'id' => '456',
        'name' => 'Jacket',
        'price' => '19900',
        'brand_name' => 'Carhartt',
        'gender' => 'f',
    ],
    [
        'id' => '789',
        'name' => 'Trousers',
        'price' => '3990',
        'brand_name' => 'Only & Sons',
        'gender' => 'f',
    ],
];

$transformer = function (array $product): array {
    return [
        'id' => (int)$product['id'],
        'name' => $product['name'],
        'price' => (int)$product['price'],
        'brand' => $product['brand_name'],
        'gender' => $product['gender'] === 'm' ? 'male' : 'female',
    ];
};

$cursor = new \League\Fractal\Pagination\Cursor(null, null, 2, 3);

$collection = $fractal->collection([
    $products[0],
    $products[1],
], $transformer)->setCursor($cursor)->toArray();