Skip to content

Instantly share code, notes, and snippets.

@vinicius73
Last active October 13, 2023 00:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vinicius73/6a2904a88ca487d53c6129f8cf8f3d6d to your computer and use it in GitHub Desktop.
Save vinicius73/6a2904a88ca487d53c6129f8cf8f3d6d to your computer and use it in GitHub Desktop.
Laravel Presenter
<?php
namespace App\Support\ViewPresenter;
trait PresentableTrait
{
/**
* View presenter instance.
*
* @var mixed
*/
protected $presenterInstance;
/**
* Prepare a new or cached presenter instance.
*
* @return mixed
*
* @throws PresenterException
*/
public function present()
{
if (! $this->presenter or ! class_exists($this->presenter)) {
throw new PresenterException('Please set the $presenter property to your presenter path.');
}
if (! $this->presenterInstance) {
$this->presenterInstance = new $this->presenter($this);
}
return $this->presenterInstance;
}
}
<?php
namespace App\Support\ViewPresenter;
use Carbon\Carbon;
use Illuminate\Support\Str;
abstract class Presenter
{
/**
* @var \Illuminate\Database\Eloquent\Model
*/
protected $entity;
/**
* @param $entity
*/
public function __construct($entity)
{
$this->entity = $entity;
}
/**
* Allow for property-style retrieval.
*
* @param $property
*
* @return mixed
*/
public function __get($property)
{
if (method_exists($this, $property)) {
return $this->{$property}();
}
return $this->entity->{$property};
}
/**
* @param Carbon $date
* @param string $fallback
*
* @return string
*/
protected function formatDateTime($date, $fallback = null)
{
return (is_null($date)) ? $fallback : $date->toDateTimeString();
}
/**
* @param Carbon $date
* @param string $fallback
* @param string $format
*
* @return string
*/
protected function formatDate($date, $fallback = null, $format = 'd/m/Y')
{
return (is_null($date)) ? $fallback : $date->format($format);
}
/**
* @param float $number
* @param string $symbol
*
* @return string
*/
protected function moneyFormat($number, $symbol = 'R$')
{
return $symbol.number_format($number, 2, ',', '.');
}
/**
* Limit a string into chars.
*
* @param string $string
* @param string $limit
* @param string $ending
*
* @return string
*/
protected function strLimitChars($string, $limit, $ending = '...')
{
return empty($limit) ? $string : Str::limit($string, $limit, $ending);
}
/**
* Limit a string into words.
*
* @param string $string
* @param string $limit
* @param string $ending
*
* @return string
*/
protected function strLimitWords($string, $limit, $ending = '...')
{
return empty($limit) ? $string : Str::words($string, $limit, $ending);
}
}
<?php
namespace App\Support\ViewPresenter;
class PresenterException extends \Exception
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment