Home >php教程 >PHP开发 >Laravel uses memcached cache to optimize article additions, deletions, modifications and searches

Laravel uses memcached cache to optimize article additions, deletions, modifications and searches

高洛峰
高洛峰Original
2016-12-28 16:34:411105browse

The example of this article describes how Laravel uses memcached cache to optimize the addition, deletion, modification and query of articles. Share it with everyone for your reference, the details are as follows:

Here we will use the addition, deletion, modification and checking of articles as an example system to describe the use of cache. This example is a RESTFul style controller created previously to implement the addition, deletion, modification and checking of articles. For the transformation and upgrade of the tutorial, we will integrate Eloquent ORM and model events based on it, and pull the application scenario directly into the generation environment.

1. Preparation work

Routing and controller

The definition of route and the creation of controller remain the same as the creation of RESTFul style controller to implement the addition, deletion, modification and check of the article.

Create data table

Regarding the data table corresponding to the article, we have already mentioned that we use the query builder to implement advanced queries on the database in the database part. Here we can use the data table created before.

Create article model

The creation of the article model Post is also consistent with what was created in the previous Eloquent ORM section about ORM overview, model definition and basic query.

2. Modify the controller

Previously we implemented the addition, deletion, modification and query operations of articles through the cache. Here we modify it to implement the addition, deletion, modification and query operations through the database:

<?php
  namespace App\Http\Controllers;
  use Illuminate\Http\Request;
  use Cache;
  use App\Models\Post;
  use App\Http\Requests;
  use App\Http\Controllers\Controller;
  class PostController extends Controller
  {
    /**
     * 显示文章列表.
     *
     * @return Response
     */
    public function index()
    {
      //使用all获取所有数据,如果数据量大采用分页获取
      $posts = Post::all();
      if(!$posts)
        exit(&#39;还没有发布任何文章!&#39;);
      $html = &#39;<ul>&#39;;
      foreach ($posts as $post) {
        $html .= &#39;<li><a href=&#39;.route(&#39;post.show&#39;,[&#39;post&#39;=>$post]).&#39;>&#39;.$post->title.&#39;</li>&#39;;
      }
      $html .= &#39;</ul>&#39;;
      return $html;
    }
    /**
     * 创建新文章表单页面
     *
     * @return Response
     */
    public function create()
    {
      $postUrl = route(&#39;post.store&#39;);
      $csrf_field = csrf_field();
      $html = <<<CREATE
        <form action="$postUrl" method="POST">
          $csrf_field
          <input type="text" name="title"><br/><br/>
          <textarea name="content" cols="50" rows="5"></textarea><br/><br/>
          <input type="submit" value="提交"/>
        </form>
CREATE;
      return $html;
}
    /**
     * 将新创建的文章存储到存储器
     *
     * @param Request $request
     * @return Response
     */
    public function store(Request $request)
    {
      $title = $request->input(&#39;title&#39;);
      $content = $request->input(&#39;content&#39;);
      $post = new Post;
      $post->title = $title;
      $post->content = $content;
      $post->save();
      return redirect()->route(&#39;post.show&#39;,[&#39;post&#39;=>$post]);
    }
    /**
     * 显示指定文章
     *
     * @param int $id
     * @return Response
     */
    public function show($id)
    {
      $post = Cache::get(&#39;post_&#39;.$id);
      if(!$post){
        $post = Post::find($id);
        if(!$post)
          exit(&#39;指定文章不存在!&#39;);
        Cache::put(&#39;post_&#39;.$id,$post,60*24*7);
      }
      if(!Cache::get(&#39;post_views_&#39;.$id))
        Cache::forever(&#39;post_views_&#39;.$id,0);
      $views = Cache::increment(&#39;post_views_&#39;.$id);
      Cache::forever(&#39;post_views_&#39;.$id,$views);
      $editUrl = route(&#39;post.edit&#39;,[&#39;post&#39;=>$post]);
      $deleteUrl = route(&#39;post.destroy&#39;,[&#39;post&#39;=>$post]);
      $html = <<<POST
        <h3>{$post->title}</h3>
        <p>{$post->content}</p>
        <i>已有{$views}人阅读</i>
        <p>
          <a href="{$editUrl}">编辑</a>
        </p>
POST;
      return $html;
    }
    /**
     * 显示编辑指定文章的表单页面
     *
     * @param int $id
     * @return Response
     */
    public function edit($id)
    {
      $post = Post::find($id);
      if(!$post)
        exit(&#39;指定文章不存在!&#39;);
      $postUrl = route(&#39;post.update&#39;,[&#39;post&#39;=>$post]);
      $csrf_field = csrf_field();
      $html = <<<CREATE
        <form action="$postUrl" method="POST">
          $csrf_field
          <input type="hidden" name="_method" value="PUT"/>
          <input type="text" name="title" value="{$post->title}"><br/><br/>
          <textarea name="content" cols="50" rows="5">{$post->content}</textarea><br/><br/>
          <input type="submit" value="提交"/>
        </form>
CREATE;
      return $html;
    }
    /**
     * 在存储器中更新指定文章
     *
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
      $post = Post::find($id);
      if(!$post)
        exit(&#39;指定文章不存在!&#39;);
      $title = $request->input(&#39;title&#39;);
      $content = $request->input(&#39;content&#39;);
      $post->title = $title;
      $post->content = $content;
      $post->save();
      return redirect()->route(&#39;post.show&#39;,[&#39;post&#39;=>$post]);
    }
    /**
     * 从存储器中移除指定文章
     *
     * @param int $id
     * @return Response
     */
    public function destroy($id)
    {
      $post = Post::find($id);
      if(!$post)
        exit(&#39;指定被删除文章不存在!&#39;);
      if($post->delete()){
        redirect()->route(&#39;post.index&#39;);
      }else{
        exit(&#39;删除文章失败!&#39;);
      }
    }
  }

It should be noted that in the show method, we first fetch the article data from the cache. If it does not exist in the cache, we will fetch it from the database. At the same time, we will write the data back to the cache. Since most operations on the database are reading, operation, so this small improvement can greatly improve performance, especially when dealing with massive data. In addition, we persist visits to the cache to improve performance.

3. Using cache in model events

We can also use model events to trigger corresponding events when articles are added, deleted, or modified to save the modifications to the cache. Here we briefly talk about model event registration. Go to the boot method of AppServiceProvider:

//保存之后更新缓存数据
Post::saved(function($post){
  $cacheKey = &#39;post_&#39;.$post->id;
  $cacheData = Cache::get($cacheKey);
  if(!$cacheData){
    Cache::add($cacheKey,$post,60*24*7);
  }else{
    Cache::put($cacheKey,$post,60*24*7);
  }
});
//删除之后清除缓存数据
Post::deleted(function($post){
  $cacheKey = &#39;post_&#39;.$post->id;
  $cacheData = Cache::get($cacheKey);
  if($cacheData){
    Cache::forget($cacheKey);
  }
  if(Cache::get(&#39;post_views_&#39;.$post->id))
    Cache::forget(&#39;post_views_&#39;.$post->id);
});

We set the cache validity period to one week. In this way, the data will be saved to the cache when the article is created or updated, and the data will also be removed from the cache when the article is deleted, thus ensuring that the deleted article cannot be browsed when viewing details.

I hope this article will be helpful to everyone’s PHP program design based on the Laravel framework.

For more information on how Laravel uses memcached caching to optimize article additions, deletions, modifications and searches, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn