PHP code example of tooleks / laravel-presenter

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

    

tooleks / laravel-presenter example snippets


'providers' => [
    ...
    Tooleks\Laravel\Presenter\Providers\PresenterProvider::class,
],



namespace App\Presenters;

use Tooleks\Laravel\Presenter\Presenter;

/**
 * Class UserPresenter.
 *
 * @property string nickname
 * @property string short_name
 * @property string full_name
 * @property string role
 */
class UserPresenter extends Presenter
{
    /**
     * @inheritdoc
     */
    protected function getAttributesMap(): array
    {
        return [
            // 'presenter_attribute_name' => 'wrapped_model_attribute_name'
            'nickname' => 'username',
            'short_name' => 'first_name',
            'full_name' => function () {
                return $this->getWrappedModelAttribute('first_name') . ' ' . $this->getWrappedModelAttribute('last_name');
            },
            'role' => 'role.name',
        ];
    }
}



$user = [ 
    'username' => 'anna',
    'first_name' => 'Anna',
    'last_name' => 'P.',
    'role' => [
        'name' => 'User',
    ],
];

$userPresenter = app()->make(\App\Presenters\UserPresenter::class)->setWrappedModel($user);
// Create the presenter from the wrapped model array.

$userPresenter = app()->make(\App\Presenters\UserPresenter::class)->setWrappedModel((object) $user);
// Create the presenter from the wrapped model object.

echo $userPresenter->nickname;
// Prints 'anna' string, as we mapped the wrapped model 'username' attribute to the presenter 'nickname' attribute.
echo $userPresenter->short_name;
// Prints 'Anna' string, as we mapped the wrapped model 'first_name' attribute to the presenter 'short_name' attribute.
echo $userPresenter->full_name;
// Prints 'Anna P.' string, as we override the presenter 'full_name' attribute by the anonymous function.
echo $userPresenter->role;
// Prints 'User' string, as we mapped the wrapped model 'role.name' nested attribute to the presenter 'role' attribute.



collect([$user])->present(\App\Presenters\UserPresenter::class);
// Create the collection of the 'UserPresenter' items.



$mappedDataArray = app()->make(\App\Presenters\UserPresenter::class)->setWrappedModel($user)->toArray();

$mappedDataObject = (object) app()->make(\App\Presenters\UserPresenter::class)->setWrappedModel($user)->toArray();



$content = app()->make(\App\Presenters\UserPresenter::class)->setWrappedModel($user);

response($content);