Laravel memcached緩衝對文章增刪改查進行最佳化例子

來源:互聯網
上載者:User

本節我們將以文章的增刪改查作為執行個體系統講述緩衝的使用,這個執行個體是對之前建立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);
});

我們將緩衝有效期間設定為一周。這樣在文章建立或更新時會將資料儲存到緩衝,而刪除文章時也會從緩衝中移除資料,從而保證被刪除後的文章查看詳情時也不能瀏覽。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.