站长资讯网
最全最丰富的资讯网站

聊聊Laravel中怎么使用 PHP 的装饰器模式

如何在 Laravel 中使用 PHP 的装饰器模式?下面本篇文章就来给大家介绍一下Laravel中使用PHP装饰器模式的方法,希望对大家有所帮助!

聊聊Laravel中怎么使用 PHP 的装饰器模式

Laravel 9 保姆级视频教程,想学不会都难!进入学习

设计模式对每个开发人员都很重要。它解决了您构建的每个项目中非常常见的问题。

装饰器模式定义:

它可以帮助您在一个对象上添加额外的行为,而又不影响同一类中的其他对象。

维基百科:

装饰器模式是一种设计模式,它允许动态地将行为添加到单个对象,而不会影响同一类中其他对象的行为

问题

假设我们有一个Post模型

class Post extends Model {     public function scopePublished($query) {         return $query->where('published_at', '<=', 'NOW()');     } }

在我们的PostsController中,我们有如下的index方法

class PostsController extends Controller {     public function index() {         $posts = Post::published()->get();         return $posts;     } }

为了缓存帖子并避免每次我们需要列出帖子时都查询数据库,我们可以执行以下操作

class PostsController extends Controller {     public function index() {         $minutes = 1440; # 1 day         $posts = Cache::remember('posts', $minutes, function () {             return Post::published()->get();         });         return $posts;     } }

现在,我们将帖子缓存1天。但看看代码,控制器了解了太多。它知道我们缓存了多少天,它自己缓存了对象。

同样,假设您正在为HomePageController的Tag,Category,Archives实现相同的功能。阅读和维护的代码太多了。

仓库模式

在大多数情况下,仓库模式是连接到装饰器模式。

首先,让我们使用仓库模式分离获取帖子的方式,创建具有以下内容的app/Repositories/Posts/PostsRepositoryInterface.php

namespace AppRepositoriesPosts;  interface PostsRepositoryInterface  {      public function get();      public function find(int $id);  }

在同个目录下创建具有下面内容的 PostsRepository

namespace AppRepositoriesPosts;  use AppPost;  class PostsRepository implements PostsRepositoryInterface {     protected $model;      public function __construct(Post $model) {         $this->model = $model;     }      public function get() {         return $this->model->published()->get();     }      public function find(int $id) {         return $this->model->published()->find($id);     }  }

回到PostsController并将更改应用为

namespace AppHttpControllers;  use AppRepositoriesPostsPostsRepositoryInterface; use IlluminateHttpRequest;  class PostsController extends Controller {     public function index(PostsRepositoryInterface $postsRepo) {         return $postsRepo->get();     } }

控制器变得健康,知道足够的细节来完成工作。

在这里,我们依靠 Laravel 的 IOC 注入 Posts 接口的具体对象来获取我们的帖子

我们需要做的就是告诉Laravel的IOC使用接口时要创建哪个类。

在你的 app/Providers/AppServiceProvider.php 添加绑定方法

namespace AppProviders;  use AppRepositoriesPostsPostsRepositoryInterface; use AppRepositoriesPostsPostsRepository;  use IlluminateSupportServiceProvider;  class AppServiceProvider extends ServiceProvider {     public function register()     {         $this->app->bind(PostsRepositoryInterface::class,PostsRepository::class);     } }

现在无论何时我们注入PostsRepositoryInterface Laravel 都会创建 PostsRepository 的实例并将其返回。

通过装饰器实现缓存

我们在一开始就说过,装饰器模式允许将行为添加到单个对象,而不会影响同一类中的其他对象。

在这里缓存是行为,对象/类是 PostsRepository

让我们在 app/Repositories/Posts/PostsCacheRepository.php 中创建具有以下内容的PostsCacheRepository

namespace AppRepositoriesPosts;  use AppPost; use IlluminateCacheCacheManager;  class PostsCacheRepository implements PostsRepositoryInterface {     protected $repo;      protected $cache;      const TTL = 1440; # 1 day      public function __construct(CacheManager $cache, PostsRepository $repo) {         $this->repo = $repo;         $this->cache = $cache;     }      public function get() {         return $this->cache->remember('posts', self::TTL, function () {             return $this->repo->get();         });     }      public function find(int $id) {         return $this->cache->remember('posts.'.$id, self::TTL, function () {             return $this->repo->find($id);         });     } }

在这个类中,我们接受 Caching 对象和 PostsRepository 对象,然后使用类(装饰器)将缓存行为添加到 PostsReposiory 实例。

我们可以使用相同的示例将HTTP请求发送到某些服务,然后在失败的情况下返回模型。我相信您会从该模式以及它是如何轻松添加行为中受益。

最后一件事是修改 AppServiceProvider 接口绑定以创建 PostsCacheRepository 实例而不是PostsRepository

namespace AppProviders;  use AppRepositoriesPostsPostsRepositoryInterface; use AppRepositoriesPostsPostsCacheRepository;  use IlluminateSupportServiceProvider;  class AppServiceProvider extends ServiceProvider {     public function register()     {         $this->app->bind(PostsRepositoryInterface::class,PostsCacheRepository::class);     } }

现在再次检查文件,您会发现它非常易于阅读和维护。同样,它也是可测试的,如果您决定在某个时候删除缓存层。您只需在AppServiceProvider中更改绑定即可。无需额外更改。

结论

  • 我们学习了如何使用修饰器模式缓存模型
  • 我们展示了仓库模式如何连接到修饰器模式
  • 依附注入和Laravel IOC如何使我们的生活变得轻松
  • laravel组件功能强大

希望您喜欢阅读本文。它向您展示了强大的设计模式,以及如何使您的项目易于维护和管理

原文地址:https://dev.to/ahmedash95/design-patterns-in-php-decorator-with-laravel-5hk6

赞(0)
分享到: 更多 (0)