首頁 php教程 PHP开发 Laravel使用memcached快取對文章增刪改查進行最佳化的方法

Laravel使用memcached快取對文章增刪改查進行最佳化的方法

Dec 28, 2016 pm 04:34 PM

本文實例講述了Laravel使用memcached快取對文章增刪改查進行最佳化的方法。分享給大家供大家參考,具體如下:

這裡我們將以文章的增刪改查作為實例係統講述緩存的使用,這個實例是對之前創建RESTFul風格控制器實現文章增刪改查這篇教程的改造和升級,我們將在其基礎上融合進Eloquent ORM和模型事件,將應用的場景直接拉到生成環境。

1、準備工作

路由及控制器

路由的定義和控制器的創建保持和創建RESTFul風格控制器實現文章增刪改查中一樣。

建立資料表

關於文章對應資料表我們在資料庫部分使用查詢建構器實現對資料庫的進階查詢已有提及,這裡我們使用先前建立的資料表即可。

創建文章模型

關於文章模型Post的創建也和之前Eloquent ORM部分講ORM概述、模型定義及基本查詢中創建的一致。

2、修改控制器

在之前我們是透過快取實現對文章的增刪改查操作,這裡我們將其修改為透過資料庫實現增刪改查操作:

<?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;);
      }
    }
  }
登入後複製

需要注意的是在show方法中,我們先從快取中取文章數據,快取中不存在才會去資料庫取,同時將資料回寫到快取中,由於對資料庫的操作大部分都是讀取操作,所以這一點小小的改進對效能卻有很大提升,尤其是在海量資料時。此外我們還將存取量持久化到快取中以提升效能。

3、在模型事件中使用快取

我們也可以透過模型事件在文章進行增刪改的時候觸發對應事件將修改儲存到快取中,這裡我們簡單講模型事件註冊到AppServiceProvider的boot方法中:

oot
//保存之后更新缓存数据
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);
});
登入後複製

我們將快取有效期限設定為一週。這樣在文章創建或更新時會將數據保存到緩存,而刪除文章時也會從緩存中移除數據,從而保證被刪除後的文章查看詳情時也不能瀏覽。

希望本文所述對大家基於Laravel框架的PHP程式設計有所幫助。

更多Laravel使用memcached快取對文章增刪改查進行最佳化的方法相關文章請關注PHP中文網!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24