guilhermegonzaga / presenter
Laravel 的 Presenter 设计模式实现。
1.0.8
2024-05-28 21:20 UTC
Requires
- php: >=5.4.0
- illuminate/database: ^5.0|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/support: ^5.0|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
Requires (Dev)
- phpunit/phpunit: ~5.2
README
Presenter 是 Laravel 的一种设计模式,用于修改从模型传递到视图的数据。
它使得数据显示以人类可理解的方式。
安装
Laravel (5.x|6.x|7.x|8.x|9.x|10.x|11.x)
执行以下命令获取此包的最新版本:
composer require guilhermegonzaga/presenter
用法
第一步是将您的展示器存储在某个地方 - 任何地方。这些将是非常简单的对象,除了格式化数据外,不做任何其他事情。
请注意,您的展示器类必须扩展 Laracodes\Presenter\Presenter
namespace App\Presenters; use Laracodes\Presenter\Presenter; class UserPresenter extends Presenter { public function fullName() { return $this->model->first_name . ' ' . $this->model->last_name; } public function accountAge() { return $this->model->created_at->diffForHumans(); } ... }
接下来,在您的模型上,引入 Laracodes\Presenter\Traits\Presentable
特性,这将自动实例化您的展示器类
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laracodes\Presenter\Traits\Presentable; class User extends Model { use Presentable; protected $presenter = 'App\Presenters\UserPresenter'; ... }
完成,现在您可以在视图中调用它
<h1>Hello, {{ $user->present()->fullName }}</h1> <h1>Hello, {{ $user->present()->full_name }}</h1> // automatically convert to camelCase
注意调用 present() 方法(将返回您的新或缓存的展示器对象)的好处,它还清楚地说明了您必须去哪里,如果您需要修改页面上的全名显示方式。
注意
当您调用其类展示器中不存在的方法时,此包将自动调用模型中的属性,并将其转换为 snake_case。
例
// automatically calls the property in the model <h1>Hello, {{ $user->present()->firstName }}</h1> // automatically convert to snake_case <h1>Hello, {{ $user->present()->first_name }}</h1>
致谢
此包主要受 此 优秀包的启发 @laracasts。