程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> Laravel使用memcached緩存對文章增刪改查進行優化的方法

Laravel使用memcached緩存對文章增刪改查進行優化的方法

編輯:PHP綜合

本文實例講述了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('還沒有發布任何文章!');
      $html = '<ul>';
      foreach ($posts as $post) {
        $html .= '<li><a href='.route('post.show',['post'=>$post]).'>'.$post->title.'</li>';
      }
      $html .= '</ul>';
      return $html;
    }
    /**
     * 創建新文章表單頁面
     *
     * @return Response
     */
    public function create()
    {
      $postUrl = route('post.store');
      $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('title');
      $content = $request->input('content');
      $post = new Post;
      $post->title = $title;
      $post->content = $content;
      $post->save();
      return redirect()->route('post.show',['post'=>$post]);
    }
    /**
     * 顯示指定文章
     *
     * @param int $id
     * @return Response
     */
    public function show($id)
    {
      $post = Cache::get('post_'.$id);
      if(!$post){
        $post = Post::find($id);
        if(!$post)
          exit('指定文章不存在!');
        Cache::put('post_'.$id,$post,60*24*7);
      }
      if(!Cache::get('post_views_'.$id))
        Cache::forever('post_views_'.$id,0);
      $views = Cache::increment('post_views_'.$id);
      Cache::forever('post_views_'.$id,$views);
      $editUrl = route('post.edit',['post'=>$post]);
      $deleteUrl = route('post.destroy',['post'=>$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('指定文章不存在!');
      $postUrl = route('post.update',['post'=>$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('指定文章不存在!');
      $title = $request->input('title');
      $content = $request->input('content');
      $post->title = $title;
      $post->content = $content;
      $post->save();
      return redirect()->route('post.show',['post'=>$post]);
    }
    /**
     * 從存儲器中移除指定文章
     *
     * @param int $id
     * @return Response
     */
    public function destroy($id)
    {
      $post = Post::find($id);
      if(!$post)
        exit('指定被刪除文章不存在!');
      if($post->delete()){
        redirect()->route('post.index');
      }else{
        exit('刪除文章失敗!');
      }
    }
  }

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

3、在模型事件中使用緩存

我們還可以通過模型事件在文章進行增刪改的時候觸發相應事件將修改保存到緩存中,這裡我們簡單講模型事件注冊到AppServiceProvider的boot方法中:

//保存之後更新緩存數據
Post::saved(function($post){
  $cacheKey = 'post_'.$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 = 'post_'.$post->id;
  $cacheData = Cache::get($cacheKey);
  if($cacheData){
    Cache::forget($cacheKey);
  }
  if(Cache::get('post_views_'.$post->id))
    Cache::forget('post_views_'.$post->id);
});

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

更多關於Laravel相關內容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php日期與時間用法總結》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved