PHP code example of brandonshar / presenters

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

    

brandonshar / presenters example snippets


use brandonshar\Presenter;

class VehicleOnCraigslistPresenter extends Presenter 
{
  protected $vehicle;
  protected $craigslistAd;
  
  public function __construct(Vehicle $vehicle, CraigslistAd $craigslistAd)
  {
    $this->vehicle = $vehicle;
    $this->craigslistAd = $craigslistAd;
  }
}

$presenter = VehicleOnCraigslistPresenter::present($vehicle, $vehicle->craiglistAd);

class VehicleOnCraigslistPresenter extends Presenter
{
  //...
  protected $delegatesTo = [
    'vehicle' => ['year', 'make'],
    'craigslistAd' => ['listedAt'],
  ];
  //...
}

$presenter = VehicleOnCraigslistPresenter::present($vehicle, $vehicle->craiglistAd);

$presenter->year; //$presenter->vehicle->year;
$presenter->make; //$presenter->vehicle->make;
$presenter->listedAt; // $presenter->craigslistAd->listedAt;

class VehicleOnCraigslistPresenter extends Presenter
{
  //...
  public function getVehicleTitleAttribute()
  {
    return "{$this->vehicle->year} {$this->vehicle->make} {$this->vehicle->model}";
  }
  
  public function getCachedAtAttribute($currentValue)
  {
    return DateTime::createFromFormat('Y-m-d', $currentValue)->format('l, M jS');
  }
  //...
}

$presenter->vehicleTitle;
//or if you prefer
$presenter->vehicle_title;

$presenter->cachedAt = '2017-09-21';
echo $presenter->cachedAt; //Thursday, Sept 21st

return $this->getAttribute('cachedAt'); 
//or (they both work the same)
return $this->getAttribute('cached_at');

public function setSomeExampleAttribute($value)
{
  $this->setAttribute('someExample', strtoupper($value));
}

$presenter->someExample = 'my message';
echo $presenter->someExample; //MY MESSAGE

$this->setAttribute('someExample', $value);
// or
$this->setAttribute('some_example', $value);

$presenter = VehicleOnCraigslistPresenter::present($vehicle, $vehicle->craiglistAd)->tap(function ($presenter) {
  $presenter->cachedAt = date('Y-m-d');
});

echo $presenter->cachedAt; //Thursday, Sept 21st (don't forget our getter from above)

echo $presenter->toJson();

echo json_encode($presenter);

return VehicleOnCraigslistPresenter::present($vehicle, $vehicle->craiglistAd)->tap(function ($p) {
  $p->cachedAt = date('Y-m-d');
});

class VehicleOnCraigslistPresenter extends Presenter
{
  //...
  protected $jsonEncodeCase = 'camel';
  //...
}