Skip to content

Instantly share code, notes, and snippets.

@abler98
Forked from Ellrion/AbstractPresenter.php
Created January 13, 2017 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abler98/1b26068116ec94c30c46e0e1426887a1 to your computer and use it in GitHub Desktop.
Save abler98/1b26068116ec94c30c46e0e1426887a1 to your computer and use it in GitHub Desktop.
Презентеры в Laravel.
<?php
namespace App\Presenters;
abstract class AbstractPresenter
{
/**
* The resource that is the object that was decorated.
*
* @var mixed
*/
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 ($this->presentMethodExists($property)) {
$method = $this->getPresentMethod($property);
return $this->{$method}();
}
return $this->entity->{$property};
}
public function __isset($property)
{
return $this->presentMethodExists($property) || isset($this->entity->{$property});
}
/**
* Allow for methods-style retrieval
*
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
return call_user_func_array([$this->entity, $name], $arguments);
}
protected function presentMethodExists($property)
{
return method_exists($this, $this->getPresentMethod($property));
}
protected function getPresentMethod($property)
{
return 'present'.studly_case($property);
}
}
<?php
namespace App\Presenters;
use App\Exceptions\PresenterNotFoundException;
trait Presentable
{
/**
* View presenter instance
*
* @var AbstractPresenter
*/
protected $presenterInstance;
/**
* Default presenters namespace.
*
* @var string
*/
protected $presentersNamespace = 'Adteam\\Presenters\\';
/**
* Prepare a new or cached presenter instance
*
* @throws PresenterNotFoundException
* @return AbstractPresenter
*/
public function present()
{
$presenter_class_name = $this->presenter ?? $this->presentersNamespace . class_basename($this) . 'Presenter';
if (!class_exists($presenter_class_name, true)) {
throw new PresenterNotFoundException($presenter_class_name);
}
if (!$this->presenterInstance) {
$this->presenterInstance = new $presenter_class_name($this);
}
return $this->presenterInstance;
}
}
<?php
namespace App\Exceptions;
use Exception;
class PresenterNotFoundException extends Exception
{
/**
* Create a new presenter not found exception.
*
* @param string $class
* @param string|null $message
* @param int $code
* @param Exception $previous
*/
public function __construct($class, $message = null, $code = 0, Exception $previous = null)
{
if (!$message) {
$message = $class.' not found. Please set the $presenter property to your presenter path.';
}
parent::__construct($message, $code, $previous);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment