Laravel Cache ::最佳实践 [英] Laravel Cache:: Best Practices

查看:627
本文介绍了Laravel Cache ::最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP同事:

此问题与使用Laravel Cache的最佳实践有关.

This question relates to best practices for using Laravel Cache.

主要目标是减少所有通常情况下对数据库的访问次数 与性能相关的原因.该应用程序是一个阅读密集的新闻站点,最多可能有十二个控制器,主要是资源类型.

The central objective is to reduce the number of accesses to the database for all the usual performance-related reasons. The application is a read-intensive news site with perhaps a dozen controllers at most, mostly resource-type.

是否有关于应用程序设计的书面最佳实践?对我来说似乎很明显 由于Cache ::是单行语句,因此很容易将其放入控制器中- 返回缓存的数据或调用模型并缓存结果.并使之无效 请求更新模型时缓存(可能有重新加载的请求).但这是一个好习惯吗?

Are there any documented best practices for the application design? It seems obvious to me that since Cache:: is a one-line statement, it's easy to drop this into the controllers -- either return the cached data or call the model and cache the results. And invalidate the cache (maybe with an eager reload) when requests update the model. But is that a good practice?

这是在控制器中执行此操作的初次观察

Here's a first look at doing this in the controller

/**
 * Retrieve listing of the gallery resource.
 *
 * @uses GET /gallery to return all image_collections.
 *
 * @param int $id The gallery id
 *
 * @return Response - Contains a HTTP code and a list of articles.
 */
public function index()
{
    $response_data = array();
    $response_code = 200;

    // TRY TO RETURN A CACHED RESPONSE
    $cache_key = "gallery_index";
    $response_data = Cache::get($cache_key, null);

    // IF NO CACHED RESPONSE, QUERY THE DATABASE
    if (!$response_data) {
        try {
            $response_data['items'] = $this->gallery->all();
            Cache::put($cache_key, $response_data, Config::get('app.gallery_cache_minutes'));
        } catch (PDOException $ex) {
            $response_code = 500;
            $response_data['error'] = ErrorReporter::raiseError($ex->getCode());
        }
    }

    return Response::json($response_data, $response_code);
}

我听说过有人建议您使用Laravel路由过滤器来缓存响应, 但我不太了解这个想法.

I've heard the suggestion that you could use Laravel Route Filters to cache the responses, but I can't quite get my head around the idea.

有什么想法吗?参考?例子吗?

Thoughts? References? Examples?

感谢所有人, 雷

推荐答案

许多人以不同的方式进行操作,但是当您关注最佳实践时,我认为最好的缓存位置是您的存储库中.

Many people do this differently but when best practices is a concern I believe the best place to do caching is in your repository.

您的控制器对数据源不应该了解太多,我的意思是说它是来自缓存还是来自数据库.

Your controller shouldn't know too much about the data source I mean whether its coming from cache or coming from database.

在控制器中缓存不支持DRY(请勿重复自己)方法,因为您发现自己在多个控制器和方法中复制代码,从而使脚本难以维护.

Caching in controller doesn't support DRY (Don't Repeat Yourself) approach, because you find yourself duplicating your code in several controllers and methods thereby making scripts difficult to maintain.

所以对我来说,这就是我使用Laravel 4时在Laravel 5中滚动的方式:

So for me this is how I roll in Laravel 5 not so different if are using laravel 4:

//1.在应用程序/存储库中创建GalleryEloquentRepository.php

//1. Create GalleryEloquentRepository.php in App/Repositories

<?php namespace App\Repositories;

use App\Models\Gallery;
use \Cache;

/**
 * Class GalleryEloquentRepository
 * @package App\Repositories
 */
class GalleryEloquentRepository implements GalleryRepositoryInterface
{

    public function all()
    {
        return Cache::remember('gallerys', $minutes='60', function()
        {
            return Gallery::all();
        });
    }


    public function find($id)
    {
        return Cache::remember("gallerys.{$id}", $minutes='60', function() use($id)
        {
            if(Cache::has('gallerys')) return Cache::has('gallerys')->find($id); //here am simply trying Laravel Collection method -find

            return Gallery::find($id);
        });
    }

}

//2.在应用程序/存储库中创建GalleryRepositoryInterface.php

//2. Create GalleryRepositoryInterface.php in App/Repositories

<?php namespace App\Repositories;

/**
 * Interface GalleryRepositoryInterface
 * @package App\Repositories
 */
interface GalleryRepositoryInterface
{

    public function find($id);

    public function all();
}

//3.在App/Providers中创建RepositoryServiceProvider.php

//3. Create RepositoryServiceProvider.php in App/Providers

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class RepositoryServiceProvider
 * @package App\Providers
 */
class RepositoryServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    //protected $defer = true;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {

        $this->app->bind(
            'App\Repositories\GalleryRepositoryInterface',
            'App\Repositories\GalleryEloquentRepository'
        );
    }
}

//4.在控制器上,您可以执行此操作

//4. At the controller you can do this

<?php namespace App\Http\Controllers;

use \View;
use App\Repositories\GalleryRepositoryInterface;

class GalleryController extends Controller {

    public function __construct(GalleryRepositoryInterface $galleryInterface)
    {
        $this->galleryInterface = $galleryInterface;

    }


    public function index()
    {
        $gallery = $this->galleryInterface->all();

        return $gallery ? Response::json($gallery->toArray()) : Response::json($gallery,500);
    }

}

这篇关于Laravel Cache ::最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆