isbkch/presenter

Simple view presenters for Laravel 5

0.5 2016-01-13 18:27 UTC

This package is auto-updated.

Last update: 2020-08-15 18:21:34 UTC


README

  • Forked at first from Laracasts/Presenters to port it to Laravel 5.2
  • But since they are no longer accepting any pull requests, I had to create my own

Easy View Presenters

So you have those scenarios where a bit of logic needs to be performed before some data (likely from your entity) is displayed from the view.

  • Should that logic be hard-coded into the view? No.
  • Should we instead store the logic in the model? No again!

Instead, leverage view presenters. That's what they're for! This package provides one such implementation.

Install

Pull this package in through Composer.

composer require isbkch/presenter

Usage

The first step is to store your presenters somewhere - anywhere. These will be simple objects that do nothing more than format data, as required.

Here's an example of a presenter.

use Isbkch\Presenter\Presenter;

class UserPresenter extends Presenter {

    public function fullName()
    {
        return $this->entity->first . ' ' . $this->entity->last;
    }

    public function accountAge()
    {
        return $this->entity->created_at->diffForHumans();
    }

}

Next, on your entity, pull in the Isbkch\Presenter\PresentableTrait trait, which will automatically instantiate your presenter class.

Here's an example in a Laravel User model.

<?php

use Isbkch\Presenter\PresentableTrait;

class User extends \Eloquent {

    use PresentableTrait;

    protected $presenter = 'UserPresenter';

}

Now, within your view, you can do:

    <h1>Hello, {{ $user->present()->fullName }}</h1>

Notice how the call to the present() method (which will return your new or cached presenter object) also provides the benefit of making it perfectly clear where you must go, should you need to modify how a full name is displayed on the page.

Have fun!

Ilyas @ http://isbkch.space