Simple and straightforward presenter implementation for Eloquent models.
You can install the package using composer
$ composer require tequilarapido/presenter
Let's assume we have a User model class
class User extends Model {
protected $fillables = ['first_name', 'last_name'];
}
- 1/ Create a presenter class like the following, and add presentation methods to it. For the example, we'll make a method that will return the user full name.
use Tequilarapido\Presenter\Presenter;
class UserPresenter extends Presenter {
public function name()
{
return $this->first_name . ' ' . $this->last_name;
}
}
We can access model property directly inside the presenter class. We can also access them via the $model property
$this->first_name
// or
$this->model->first_name
// or
$this->model->getAttribute('first_name')
- 2/ you need to reference this class in the model using a public
$presenter
property and use thePrensentable
trait.
use Tequilarapido\Presenter\Presentable;
class User extends Model {
use Presentable;
protected $fillables = ['first_name', 'last_name'];
public $presenter = UserPresenter::class;
}
- 3/ You can than get the presented value like so :
$user = User::find(1);
// Retreive as property
$user->present()->name
// you can alse call the method
$user->present()->name()
Please see CHANGELOG for more information what has changed recently.
$ composer test
If you discover any security related issues, please email :author_email instead of using the issue tracker.
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.