PHP code example of andrewdyer / view-presenters

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

    

andrewdyer / view-presenters example snippets




namespace App\Presenters;

use App\Models\User;
use Anddye\ViewPresenters\Presenter;

class UserPresenter extends Presenter
{
    public function __construct(readonly private User $user) {}

    public function defaultAttributes(): array
    {
        return [
            'id' => $this->user->getId(),
            'forename' => $this->user->getForename(),
            'surname' => $this->user->getSurname(),
        ];
    }

    public function name(): string
    {
        return $this->user->getForename() . ' ' . $this->user->getSurname();
    }
}



namespace App\Models;

use App\Presenters\UserPresenter;
use Anddye\ViewPresenters\HasPresenters;

class User {
    use HasPresenters;

    protected int $id;
    protected string $forename;
    protected string $surname;
    protected array $presenters = [
        'default' => UserPresenter::class,
    ];

    public function getId(): int
    {
        return $this->id;
    }

    public function getForename(): string
    {
        return $this->forename;
    }

    public function getSurname(): string
    {
        return $this->surname;
    }
}

$user = new User();
$user->setId(1);
$user->setForename('John');
$user->setSurname('Doe');

echo $user->present()->name; // "John Doe"