Skip to content

Commit

Permalink
add caching with redis
Browse files Browse the repository at this point in the history
  • Loading branch information
pashaapsky committed Nov 2, 2020
1 parent a794ea9 commit 209360c
Show file tree
Hide file tree
Showing 22 changed files with 311 additions and 60 deletions.
7 changes: 4 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@ DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_PREFIX=apsky_laravel_database_

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
Expand Down
25 changes: 25 additions & 0 deletions app/Events/News/NewsCreated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Events;

use App\News;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewsCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public News $news;

/**
* Create a new event instance.
*
* @param News $news
*/
public function __construct(News $news)
{
$this->news = $news;
}
}
25 changes: 25 additions & 0 deletions app/Events/News/NewsDeleted.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Events;

use App\News;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewsDeleted
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public News $news;

/**
* Create a new event instance.
*
* @param News $news
*/
public function __construct(News $news)
{
$this->news = $news;
}
}
25 changes: 25 additions & 0 deletions app/Events/News/NewsUpdated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Events;

use App\News;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewsUpdated
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public News $news;

/**
* Create a new event instance.
*
* @param News $news
*/
public function __construct(News $news)
{
$this->news = $news;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@ class PostCreated

public Post $post;

/**
* Create a new event instance.
*
* @param Post $post
*/
public function __construct(Post $post)
{
$this->post = $post;
Expand Down
20 changes: 20 additions & 0 deletions app/Events/Posts/PostDeleted.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace App\Events;

use App\Post;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PostDeleted
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public Post $post;

public function __construct(Post $post)
{
$this->post = $post;
}
}
File renamed without changes.
File renamed without changes.
11 changes: 9 additions & 2 deletions app/Http/Controllers/AdministrationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\News;
use App\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AdministrationController extends Controller
{
Expand All @@ -18,12 +19,18 @@ public function index() {
}

public function posts() {
$posts = Post::with('tags')->latest()->get();
$posts = Cache::tags('posts')->remember('user_posts|' . auth()->id(), 3600, function () {
return auth()->user()->posts()->with(['tags', 'comments'])->latest()->get();
});

return view('/admin.posts', compact('posts'));
}

public function news() {
$news = News::latest()->get();
$news = Cache::tags('news')->remember('users_news|' . auth()->id(), 3600, function () {
return News::with(['tags', 'comments'])->latest()->get();
});

return view('/admin.news', compact('news'));
}

Expand Down
11 changes: 9 additions & 2 deletions app/Http/Controllers/FeedbacksController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
namespace App\Http\Controllers;

use App\Feedback;
use Illuminate\Filesystem\Cache;
use Illuminate\Http\Request;

class FeedbacksController extends Controller
{
public function __construct()
{
$this->middleware('role:admin');
$this->middleware('role:admin')->except('store');
}

public function index()
Expand All @@ -28,6 +29,12 @@ public function store(Request $request)

Feedback::create($request->all());

return redirect('/admin/feedbacks');
flash('Feedback successfully send (:', 'success');

if (auth()->user() && auth()->user()->hasRole('admin')) {
return redirect('/admin/feedbacks');
} else {
return back();
}
}
}
10 changes: 6 additions & 4 deletions app/Http/Controllers/NewsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
namespace App\Http\Controllers;

use App\News;
use App\NewTag;
use App\Services\TagsCreatorService;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;

class NewsController extends Controller
Expand All @@ -27,7 +27,11 @@ public function validateRequest($request, $new)

public function index()
{
$news = News::with(['tags', 'comments'])->latest()->get();
$news = Cache::tags('news')->remember('users_news|' . auth()->id(), 3600, function () {
return News::with(['tags', 'comments'])->latest()->get();
});

// $news = News::with(['tags', 'comments'])->latest()->get();

return view('news.index', compact('news'));
}
Expand Down Expand Up @@ -75,8 +79,6 @@ public function update(Request $request, News $new)
$updater = new TagsCreatorService($new, $request);
$updater->updateTags();

// updateTags($new, $request);

flash( 'New updated successfully');

return back();
Expand Down
7 changes: 5 additions & 2 deletions app/Http/Controllers/PostsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
use App\Notifications\PostDeleted;
use App\Notifications\PostEdited;
use App\Post;
use App\PostTag;
use App\Services\TagsCreatorService;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;

class PostsController extends Controller
Expand All @@ -31,7 +31,10 @@ public function validateRequest($request, $post)

public function index()
{
$posts = auth()->user()->posts()->with(['tags', 'comments'])->latest()->get();
$posts = Cache::tags('posts')->remember('user_posts|' . auth()->id(), 3600, function () {
return auth()->user()->posts()->with(['tags', 'comments'])->latest()->get();
});

return view('/posts.index', compact('posts'));
}

Expand Down
71 changes: 37 additions & 34 deletions app/Http/Controllers/StaticPagesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Http\Controllers;

use App\Services\StatisticService;
use Illuminate\Support\Facades\Cache;

class StaticPagesController extends Controller
{
Expand All @@ -22,40 +23,42 @@ public function aboutIndex() {
}

public function statisticsIndex() {
//Общее количество статей
$postsCount = $this->statisticService->getPostsCount();

//Общее количество новостей
$newsCount = $this->statisticService->getNewsCount();

//ФИО автора, у которого больше всего статей на сайте
$userWithMostPosts = $this->statisticService->getUserWithMaxPosts();

//Самая длинная статья - название, ссылка на статью и длина статьи в символах
$theLongestPost = $this->statisticService->getTheLongestPost();

//Самая короткая статья - название, ссылка на статью и длина статьи в символах
$theShortestPost = $this->statisticService->getTheShortestPost();

//Средние количество статей у “активных” пользователей, при этом активным пользователь считается, если у него есть более 1-й статьи
$avgPostsHaveActiveUsers = $this->statisticService->getAveragePosts();

//Самая непостоянная - название, ссылка на статью, которую меняли больше всего раз
$mostChangingPost = $this->statisticService->getMostChangingPost();

//Самая обсуждаемая статья - название, ссылка на статью, у которой больше всего комментариев.
$mostCommentPost = $this->statisticService->getMostCommentPost();

$statistics = [
'posts_count' => $postsCount,
'news_count' => $newsCount,
'user_with_most_posts' => $userWithMostPosts,
'the_longest_post' => $theLongestPost,
'the_shortest_post' => $theShortestPost,
'avg_posts_have_active_users' => $avgPostsHaveActiveUsers,
'most_changing_post' => $mostChangingPost,
'most_comment_post' => $mostCommentPost
];
$statistics = Cache::tags('statistics_data')->remember('statistics_data', 3600, function () {
//Общее количество статей
$postsCount = $this->statisticService->getPostsCount();

//Общее количество новостей
$newsCount = $this->statisticService->getNewsCount();

//ФИО автора, у которого больше всего статей на сайте
$userWithMostPosts = $this->statisticService->getUserWithMaxPosts();

//Самая длинная статья - название, ссылка на статью и длина статьи в символах
$theLongestPost = $this->statisticService->getTheLongestPost();

//Самая короткая статья - название, ссылка на статью и длина статьи в символах
$theShortestPost = $this->statisticService->getTheShortestPost();

//Средние количество статей у “активных” пользователей, при этом активным пользователь считается, если у него есть более 1-й статьи
$avgPostsHaveActiveUsers = $this->statisticService->getAveragePosts();

//Самая непостоянная - название, ссылка на статью, которую меняли больше всего раз
$mostChangingPost = $this->statisticService->getMostChangingPost();

//Самая обсуждаемая статья - название, ссылка на статью, у которой больше всего комментариев.
$mostCommentPost = $this->statisticService->getMostCommentPost();

return [
'posts_count' => $postsCount,
'news_count' => $newsCount,
'user_with_most_posts' => $userWithMostPosts,
'the_longest_post' => $theLongestPost,
'the_shortest_post' => $theShortestPost,
'avg_posts_have_active_users' => $avgPostsHaveActiveUsers,
'most_changing_post' => $mostChangingPost,
'most_comment_post' => $mostCommentPost
];
});

return view('static.statistics', ['statistics' => $statistics]);
}
Expand Down
9 changes: 9 additions & 0 deletions app/News.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace App;

use App\Events\NewsCreated;
use App\Events\NewsDeleted;
use App\Events\NewsUpdated;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

Expand All @@ -11,6 +14,12 @@ class News extends Model

protected $guarded = [];

protected $dispatchesEvents = [
'created' => NewsCreated::class,
'updated' => NewsUpdated::class,
'deleted' => NewsDeleted::class
];

public function tags()
{
// return $this->belongsToMany(Tag::class, 'new_tag', 'new_id', 'tag_id');
Expand Down
42 changes: 42 additions & 0 deletions app/Observers/NewsObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace App\Observers;

use App\News;
use Illuminate\Support\Facades\Cache;

class NewsObserver
{
/**
* Handle the news "created" event.
*
* @param \App\News $news
* @return void
*/
public function created(News $news)
{
Cache::tags(['news', 'latest_news', 'statistics_data', 'tags_cloud'])->flush();
}

/**
* Handle the news "updated" event.
*
* @param \App\News $news
* @return void
*/
public function updated(News $news)
{
Cache::tags(['news', 'latest_news', 'statistics_data', 'tags_cloud'])->flush();
}

/**
* Handle the news "deleted" event.
*
* @param \App\News $news
* @return void
*/
public function deleted(News $news)
{
Cache::tags(['news', 'latest_news', 'statistics_data', 'tags_cloud'])->flush();
}
}
Loading

0 comments on commit 209360c

Please sign in to comment.