【问题标题】:Properly cache a type-hinted model in Laravel在 Laravel 中正确缓存类型提示的模型
【发布时间】:2022-01-25 10:14:00
【问题描述】:

我正在使用 Redis 来缓存我的应用程序的不同部分。我的目标是在用户未登录时不进行数据库查询,因为应用的内容不会定期更新。

我在控制器中缓存存档查询,但是当我在控制器中键入提示模型时,模型会从数据库中检索,然后传递给控制器​​:

// My route
Route::get('page/{page:id}', [ PageController::class, 'show' ] );

// My controller
public function show ( Page $page ) {
    // Here, the $page will be the actual page model. 
    // It's already been queried from the database.
}

我要做的是先尝试从缓存中解析页面,然后如果缓存中不包含此项,则查询数据库。如果我放弃 Page 类型提示,我会得到想要的结果(只有 id 被传递给控制器​​)​​但是我将失去 IoC、自动 ModelNotFoundException 等的好处。

我遇到过一些想法,例如将页面模型绑定到回调,然后解析 request(),但这似乎是个坏主意。

有什么方法可以正确实现这一点吗?我注意到 Laravel eloquent 没有 fetching 事件,这对于这个目的来说是完美的。

【问题讨论】:

    标签: php laravel caching eloquent


    【解决方案1】:

    您可以覆盖默认的模型绑定逻辑:

    Models\Page.php

    public function resolveRouteBinding($value, $field = null)
    {
        return \Cache::get(...) ?? $this->findOrFail($value);
    }
    

    在此处阅读更多信息https://laravel.com/docs/8.x/routing#customizing-the-resolution-logic

    【讨论】:

      【解决方案2】:

      为了检查 Redis 中的数据是否存在,您不应将模型类型提示到控制器的操作中。这样做:

      public function show($pageId) {
      
          if(/* check if cached */) {
              // Read page from cache
          } else {
              Page::where('id', $pageId)->first();
          }
          
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-24
        • 2021-01-25
        • 2018-04-21
        • 1970-01-01
        • 2021-06-21
        • 2017-07-29
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        相关资源
        最近更新 更多