Laravel memcached Cache Optimization Example of adding and deleting articles and checking

Source: Internet
Author: User
Tags memcached

In this section, we will use the article's additions and deletions as an instance system to describe the cache usage, this example is to create RESTful style controller before the implementation of the article additions and deletions to check this tutorial transformation and upgrade, we will be based on the integration of eloquent ORM and model events, the application of the scene directly pull to the build environment.

1. Preparation work

Routing and Controller

The definition of the route and the creation of the controller maintain and create the RESTful style controller to achieve the same article additions and deletions.

Creating data Tables

about the article corresponding datasheet we use the Query Builder in the database section to implement advanced queries to the database, and here we use the data table we created earlier.

Create an article model

The creation of the article model post is also consistent with the ORM overview, the model definition, and the creation of the basic query that preceded the eloquent ORM section.

2, modify the controller

In the past we are through the cache to add and delete the article to check the operation, here we will modify it to the database to implement additions and deletions to check operations:

<?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
    {
        /**
         * Displays a list of articles.
          *
         * @return Response
          */
        Public Function index ()
        {
            //Use all to get all the data, if the amount of data used paging get
            $posts = Post::all ();
            if (! $posts)
                 exit (' hasn't published any articles yet! ');

$html = ' <ul> ';

foreach ($posts as $post) {
$html. = ' <li><a href= '. Route (' Post.show ', [' Post ' => $post]). ' > '. $post->title. ' </li> ';
}

$html. = ' </ul> ';

return $html;
}

/**
* Create new Article form page
*
* @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= "rows=" 5 "></textarea><br/><br/>
<input type= "Submit" value= "submitted"/>
</form>
CREATE;
return $html;
}

/**
* Store the newly created article in memory
*
* @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]);
}

       /**
         * Display specified articles
         *
         * param int $id
         * @return Response
          */
        public Function Show ($id)
         {

            $post = cache::get (' post_ '. $id);
            if (! $post) {
                 $post = Post::find ($id);
                if (! $post)
                     Exit (' specified article does not exist! ');
                Cache::p ut (' 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
<p>{$post->content}</p>
<i> already have {$views} people reading </i>
<p>
<a href= "{$editUrl}" > Edit </a>
</p>
POST;

return $html;
}

/**
* Display the form page that edits the specified article
*
* @param int $id
* @return Response
*/
Public function edit ($id)
{
$post = Post::find ($id);

if (! $post)
Exit (' Specifies that the article does not exist! ');

$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= "rows=" 5 ">{$post->content}</textarea><br/><br/>
<input type= "Submit" value= "submitted"/>
</form>
CREATE;
return $html;

}

       /**
         * Update the specified article in storage
         *
          * @param Request $request
         * @param int $id
  & nbsp;      * @return Response
         */
        Public Function Update (Request $request, $id)
         {
            $post = post:: Find ($id);
            if (! $post)
                 exit (' specified article does not exist! ');

$title = $request->input (' title ');
$content = $request->input (' content ');

$post->title = $title;
$post->content = $content;

$post->save ();

Return Redirect ()->route (' Post.show ', [' Post ' => $post]);
}

       /**
         * Remove the specified article from storage
         *
          * @param int $id
         * @return Response
   & nbsp;     */
        public Function Destroy ($id)
        {
             $post = Post::find ($id);
            if (! $post)
                 exit (' Specify deleted article does not exist! ');

if ($post->delete ()) {
Redirect ()->route (' Post.index ');
}else{
Exit (' Delete article failed! ');
}
}
}

It should be noted that in the Show method, we first take the article data from the cache, the cache does not exist will go to the database, while the data back to the cache, because most of the operation of the database is read operation, so this little improvement on the performance has been greatly improved, especially in the massive data. In addition, we persist the amount of traffic to the cache to improve performance.

3. Using caching in model events

We can also through the model event in the article to add or delete changes to trigger the corresponding event to save the change to the cache, here we simply talk about model events registered to the Appserviceprovider boot method:

Update cached data after saving
Post::saved (function ($post) {
$cacheKey = ' post_ '. $post->id;
$cacheData = Cache::get ($cacheKey);
if (! $cacheData) {
Cache::add ($cacheKey, $post, 60*24*7);
}else{
Cache::p ut ($cacheKey, $post, 60*24*7);
}
});

Purge cached data after deletion
Post::d eleted (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);
});

We set the cache validity period to one week. This saves the data to the cache when the article is created or updated, while deleting the article removes the data from the cache, ensuring that the deleted article is not browsable when it is viewed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.