- PHP 100%
- Flatten PSR-0 src/LithiumHosting/Presenter/* to PSR-4 src/* - composer.json: PHP ^8.2 constraint, drop dead require-dev (phpspec/mockery v0-era), drop illuminate/support (the package has no Laravel-specific dependency) - strict_types + type hints throughout - Presenter::__construct uses constructor property promotion - PresentableTrait throws when $presenter is unset or unknown, returns a typed Presenter - README rewritten with a complete usage example - Stripped proprietary copyright headers; package is MIT Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|---|---|---|
| src | ||
| .gitattributes | ||
| .gitignore | ||
| composer.json | ||
| LICENSE.md | ||
| README.md | ||
Laravel Presenter
Minimal view-presenter base class plus a trait. The PresentableTrait
adds a present() accessor to your model; the Presenter base class
wraps the entity and exposes computed fields through property-style
access. Tested on PHP 8.2+, framework-agnostic but designed to live
alongside Laravel models.
Inspired by Jeffrey Way's original Laracasts Presenter package, modernized for PHP 8.2 and slimmed down.
Installation
composer require lithiumhosting/laravel-presenter
Usage
Declare a Presenter for the fields you want to compute:
use LithiumHosting\Presenter\Presenter;
class UserPresenter extends Presenter
{
public function fullName(): string
{
return trim($this->entity->first_name.' '.$this->entity->last_name);
}
public function avatarUrl(): string
{
return 'https://gravatar.com/avatar/'.md5(strtolower($this->entity->email));
}
}
Add the trait + presenter pointer to the model:
use LithiumHosting\Presenter\PresentableTrait;
class User extends Model
{
use PresentableTrait;
protected string $presenter = UserPresenter::class;
}
Then in views:
{{ $user->present()->fullName }}
<img src="{{ $user->present()->avatarUrl }}">
The presenter falls through to the underlying entity when no matching
method exists, so $user->present()->email still returns the raw email
column.
License
This package, laravel-presenter is licensed under The MIT License (MIT). Please see License File for more information.
Is it any good?
Yes.
When people first hear about a new product, they frequently ask if it is any good. A Hacker News user remarked:
Note to self: Starting immediately, all raganwald projects will have a "Is it any good?" section in the readme, and the answer shall be "yes.".