PHP code example of locomotivemtl / charcoal-presenter

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

    

locomotivemtl / charcoal-presenter example snippets


$presenter = new Presenter([
    'id',
    'name',
    'display_date'
]);

$model = $factory->create(Model::class);
$viewData = $presenter->transform($model);

$presenter = new Presenter(function($model) {
    return [
        'id',
        'name',
        'display_date' => $model->date->format('Y-m-d')
    ];
});

$model = $factory->create(Model::class);
$viewData = $presenter->transform($model);


class MyTransformer
{
    /**
     * @var string $dateFormat
     */
    private $dateFormat;
    
    /**
     * @param string $dateFormat The date format.
     */
    public function __construct($dateFormat)
    {
        $this->dateFormat = $dateFormat;
    }

    /**
     * @param mixed $model The model to transform.
     * @return array
     */
    public function __invoke($model)
    {
        $displayDate = $obj->date->format($this->dateFormat);
        return [
            'id',
            'name',
            'display_date'=>$displayDate
        ];
    }
}

$presenter = new Presenter(new MyTransformer('Y-m-d'));

$model = $factory->create(Model::class);
$viewData = $presenter->transform($model);