n7olkachev / php-simple-delegator
PHP的简单装饰器特性
v1.0.0
2017-08-28 13:58 UTC
Requires
- php: ^7.0
Requires (Dev)
- phpunit/phpunit: ^5.7
This package is auto-updated.
Last update: 2024-09-23 21:29:26 UTC
README
为什么?
您可以观看Jeffrey Way在Laracon US 2017的演示视频,其中包含使用示例:https://streamacon.com/video/laracon-us-2017/day-2-jeffrey-way(35:00)
示例
假设,我们想要为我们的User模型创建一个展示者
class User extends Model { protected $fillable = [ 'name', ]; } class UserPresenter { use SimpleDelegator; protected $user; public function __construct($user) { $this->user = $user; } protected function delegatee() { return $this->user; } public function formattedName() { return 'Decorated ' . $this->user->name; } } $decoratedUser = new UserPresenter($user); $decoratedUser->formattedName() // call to decorator method $decoratedUser->name // gets original name from User model
或者,我们想要为我们的类添加一些额外的行为(如在Jeffrey的示例中)
class NotifyingThread { protected $thread; public function __construct($thread) { $this->thread = $thread; } public function addReply() { $reply = $this->thread->addReply(); Notification::send( $reply->mentionedUsers(), new YouWereMentioned($reply) ); } } $thread = new NotifyingThread($thread); $thread->addReply($data); // default logic + sending notification
安装
您可以通过composer安装此包
composer require n7olkachev/php-simple-delegator
然后,将SimpleDelegator特性添加到您的装饰器类中
use SimpleDelegator;
测试
$ composer test
致谢
赞助商
位于白俄罗斯明斯克的网络代理机构
许可证
MIT许可证(MIT)