Skip to content

Commit 209360c

Browse files
committed
add caching with redis
1 parent a794ea9 commit 209360c

22 files changed

+311
-60
lines changed

.env.example

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,16 @@ DB_DATABASE=laravel
1313
DB_USERNAME=root
1414
DB_PASSWORD=
1515

16-
BROADCAST_DRIVER=log
17-
CACHE_DRIVER=file
18-
QUEUE_CONNECTION=sync
16+
BROADCAST_DRIVER=redis
17+
CACHE_DRIVER=redis
18+
QUEUE_CONNECTION=redis
1919
SESSION_DRIVER=file
2020
SESSION_LIFETIME=120
2121

2222
REDIS_HOST=127.0.0.1
2323
REDIS_PASSWORD=null
2424
REDIS_PORT=6379
25+
REDIS_PREFIX=apsky_laravel_database_
2526

2627
MAIL_MAILER=smtp
2728
MAIL_HOST=smtp.mailtrap.io

app/Events/News/NewsCreated.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace App\Events;
4+
5+
use App\News;
6+
use Illuminate\Broadcasting\InteractsWithSockets;
7+
use Illuminate\Foundation\Events\Dispatchable;
8+
use Illuminate\Queue\SerializesModels;
9+
10+
class NewsCreated
11+
{
12+
use Dispatchable, InteractsWithSockets, SerializesModels;
13+
14+
public News $news;
15+
16+
/**
17+
* Create a new event instance.
18+
*
19+
* @param News $news
20+
*/
21+
public function __construct(News $news)
22+
{
23+
$this->news = $news;
24+
}
25+
}

app/Events/News/NewsDeleted.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace App\Events;
4+
5+
use App\News;
6+
use Illuminate\Broadcasting\InteractsWithSockets;
7+
use Illuminate\Foundation\Events\Dispatchable;
8+
use Illuminate\Queue\SerializesModels;
9+
10+
class NewsDeleted
11+
{
12+
use Dispatchable, InteractsWithSockets, SerializesModels;
13+
14+
public News $news;
15+
16+
/**
17+
* Create a new event instance.
18+
*
19+
* @param News $news
20+
*/
21+
public function __construct(News $news)
22+
{
23+
$this->news = $news;
24+
}
25+
}

app/Events/News/NewsUpdated.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace App\Events;
4+
5+
use App\News;
6+
use Illuminate\Broadcasting\InteractsWithSockets;
7+
use Illuminate\Foundation\Events\Dispatchable;
8+
use Illuminate\Queue\SerializesModels;
9+
10+
class NewsUpdated
11+
{
12+
use Dispatchable, InteractsWithSockets, SerializesModels;
13+
14+
public News $news;
15+
16+
/**
17+
* Create a new event instance.
18+
*
19+
* @param News $news
20+
*/
21+
public function __construct(News $news)
22+
{
23+
$this->news = $news;
24+
}
25+
}

app/Events/PostCreated.php renamed to app/Events/Posts/PostCreated.php

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,6 @@ class PostCreated
1212

1313
public Post $post;
1414

15-
/**
16-
* Create a new event instance.
17-
*
18-
* @param Post $post
19-
*/
2015
public function __construct(Post $post)
2116
{
2217
$this->post = $post;

app/Events/Posts/PostDeleted.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace App\Events;
4+
5+
use App\Post;
6+
use Illuminate\Broadcasting\InteractsWithSockets;
7+
use Illuminate\Foundation\Events\Dispatchable;
8+
use Illuminate\Queue\SerializesModels;
9+
10+
class PostDeleted
11+
{
12+
use Dispatchable, InteractsWithSockets, SerializesModels;
13+
14+
public Post $post;
15+
16+
public function __construct(Post $post)
17+
{
18+
$this->post = $post;
19+
}
20+
}
File renamed without changes.

app/Http/Controllers/AdministrationController.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use App\News;
66
use App\Post;
77
use Illuminate\Http\Request;
8+
use Illuminate\Support\Facades\Cache;
89

910
class AdministrationController extends Controller
1011
{
@@ -18,12 +19,18 @@ public function index() {
1819
}
1920

2021
public function posts() {
21-
$posts = Post::with('tags')->latest()->get();
22+
$posts = Cache::tags('posts')->remember('user_posts|' . auth()->id(), 3600, function () {
23+
return auth()->user()->posts()->with(['tags', 'comments'])->latest()->get();
24+
});
25+
2226
return view('/admin.posts', compact('posts'));
2327
}
2428

2529
public function news() {
26-
$news = News::latest()->get();
30+
$news = Cache::tags('news')->remember('users_news|' . auth()->id(), 3600, function () {
31+
return News::with(['tags', 'comments'])->latest()->get();
32+
});
33+
2734
return view('/admin.news', compact('news'));
2835
}
2936

app/Http/Controllers/FeedbacksController.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@
33
namespace App\Http\Controllers;
44

55
use App\Feedback;
6+
use Illuminate\Filesystem\Cache;
67
use Illuminate\Http\Request;
78

89
class FeedbacksController extends Controller
910
{
1011
public function __construct()
1112
{
12-
$this->middleware('role:admin');
13+
$this->middleware('role:admin')->except('store');
1314
}
1415

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

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

31-
return redirect('/admin/feedbacks');
32+
flash('Feedback successfully send (:', 'success');
33+
34+
if (auth()->user() && auth()->user()->hasRole('admin')) {
35+
return redirect('/admin/feedbacks');
36+
} else {
37+
return back();
38+
}
3239
}
3340
}

app/Http/Controllers/NewsController.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
namespace App\Http\Controllers;
44

55
use App\News;
6-
use App\NewTag;
76
use App\Services\TagsCreatorService;
87
use App\Tag;
98
use Illuminate\Http\Request;
9+
use Illuminate\Support\Facades\Cache;
1010
use Illuminate\Validation\Rule;
1111

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

2828
public function index()
2929
{
30-
$news = News::with(['tags', 'comments'])->latest()->get();
30+
$news = Cache::tags('news')->remember('users_news|' . auth()->id(), 3600, function () {
31+
return News::with(['tags', 'comments'])->latest()->get();
32+
});
33+
34+
// $news = News::with(['tags', 'comments'])->latest()->get();
3135

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

78-
// updateTags($new, $request);
79-
8082
flash( 'New updated successfully');
8183

8284
return back();

app/Http/Controllers/PostsController.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66
use App\Notifications\PostDeleted;
77
use App\Notifications\PostEdited;
88
use App\Post;
9-
use App\PostTag;
109
use App\Services\TagsCreatorService;
1110
use App\Tag;
1211
use Illuminate\Http\Request;
12+
use Illuminate\Support\Facades\Cache;
1313
use Illuminate\Validation\Rule;
1414

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

3232
public function index()
3333
{
34-
$posts = auth()->user()->posts()->with(['tags', 'comments'])->latest()->get();
34+
$posts = Cache::tags('posts')->remember('user_posts|' . auth()->id(), 3600, function () {
35+
return auth()->user()->posts()->with(['tags', 'comments'])->latest()->get();
36+
});
37+
3538
return view('/posts.index', compact('posts'));
3639
}
3740

app/Http/Controllers/StaticPagesController.php

Lines changed: 37 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Http\Controllers;
44

55
use App\Services\StatisticService;
6+
use Illuminate\Support\Facades\Cache;
67

78
class StaticPagesController extends Controller
89
{
@@ -22,40 +23,42 @@ public function aboutIndex() {
2223
}
2324

2425
public function statisticsIndex() {
25-
//Общее количество статей
26-
$postsCount = $this->statisticService->getPostsCount();
27-
28-
//Общее количество новостей
29-
$newsCount = $this->statisticService->getNewsCount();
30-
31-
//ФИО автора, у которого больше всего статей на сайте
32-
$userWithMostPosts = $this->statisticService->getUserWithMaxPosts();
33-
34-
//Самая длинная статья - название, ссылка на статью и длина статьи в символах
35-
$theLongestPost = $this->statisticService->getTheLongestPost();
36-
37-
//Самая короткая статья - название, ссылка на статью и длина статьи в символах
38-
$theShortestPost = $this->statisticService->getTheShortestPost();
39-
40-
//Средние количество статей у “активных” пользователей, при этом активным пользователь считается, если у него есть более 1-й статьи
41-
$avgPostsHaveActiveUsers = $this->statisticService->getAveragePosts();
42-
43-
//Самая непостоянная - название, ссылка на статью, которую меняли больше всего раз
44-
$mostChangingPost = $this->statisticService->getMostChangingPost();
45-
46-
//Самая обсуждаемая статья - название, ссылка на статью, у которой больше всего комментариев.
47-
$mostCommentPost = $this->statisticService->getMostCommentPost();
48-
49-
$statistics = [
50-
'posts_count' => $postsCount,
51-
'news_count' => $newsCount,
52-
'user_with_most_posts' => $userWithMostPosts,
53-
'the_longest_post' => $theLongestPost,
54-
'the_shortest_post' => $theShortestPost,
55-
'avg_posts_have_active_users' => $avgPostsHaveActiveUsers,
56-
'most_changing_post' => $mostChangingPost,
57-
'most_comment_post' => $mostCommentPost
58-
];
26+
$statistics = Cache::tags('statistics_data')->remember('statistics_data', 3600, function () {
27+
//Общее количество статей
28+
$postsCount = $this->statisticService->getPostsCount();
29+
30+
//Общее количество новостей
31+
$newsCount = $this->statisticService->getNewsCount();
32+
33+
//ФИО автора, у которого больше всего статей на сайте
34+
$userWithMostPosts = $this->statisticService->getUserWithMaxPosts();
35+
36+
//Самая длинная статья - название, ссылка на статью и длина статьи в символах
37+
$theLongestPost = $this->statisticService->getTheLongestPost();
38+
39+
//Самая короткая статья - название, ссылка на статью и длина статьи в символах
40+
$theShortestPost = $this->statisticService->getTheShortestPost();
41+
42+
//Средние количество статей у “активных” пользователей, при этом активным пользователь считается, если у него есть более 1-й статьи
43+
$avgPostsHaveActiveUsers = $this->statisticService->getAveragePosts();
44+
45+
//Самая непостоянная - название, ссылка на статью, которую меняли больше всего раз
46+
$mostChangingPost = $this->statisticService->getMostChangingPost();
47+
48+
//Самая обсуждаемая статья - название, ссылка на статью, у которой больше всего комментариев.
49+
$mostCommentPost = $this->statisticService->getMostCommentPost();
50+
51+
return [
52+
'posts_count' => $postsCount,
53+
'news_count' => $newsCount,
54+
'user_with_most_posts' => $userWithMostPosts,
55+
'the_longest_post' => $theLongestPost,
56+
'the_shortest_post' => $theShortestPost,
57+
'avg_posts_have_active_users' => $avgPostsHaveActiveUsers,
58+
'most_changing_post' => $mostChangingPost,
59+
'most_comment_post' => $mostCommentPost
60+
];
61+
});
5962

6063
return view('static.statistics', ['statistics' => $statistics]);
6164
}

app/News.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
namespace App;
44

5+
use App\Events\NewsCreated;
6+
use App\Events\NewsDeleted;
7+
use App\Events\NewsUpdated;
58
use Illuminate\Database\Eloquent\Factories\HasFactory;
69
use Illuminate\Database\Eloquent\Model;
710

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

1215
protected $guarded = [];
1316

17+
protected $dispatchesEvents = [
18+
'created' => NewsCreated::class,
19+
'updated' => NewsUpdated::class,
20+
'deleted' => NewsDeleted::class
21+
];
22+
1423
public function tags()
1524
{
1625
// return $this->belongsToMany(Tag::class, 'new_tag', 'new_id', 'tag_id');

app/Observers/NewsObserver.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
namespace App\Observers;
4+
5+
use App\News;
6+
use Illuminate\Support\Facades\Cache;
7+
8+
class NewsObserver
9+
{
10+
/**
11+
* Handle the news "created" event.
12+
*
13+
* @param \App\News $news
14+
* @return void
15+
*/
16+
public function created(News $news)
17+
{
18+
Cache::tags(['news', 'latest_news', 'statistics_data', 'tags_cloud'])->flush();
19+
}
20+
21+
/**
22+
* Handle the news "updated" event.
23+
*
24+
* @param \App\News $news
25+
* @return void
26+
*/
27+
public function updated(News $news)
28+
{
29+
Cache::tags(['news', 'latest_news', 'statistics_data', 'tags_cloud'])->flush();
30+
}
31+
32+
/**
33+
* Handle the news "deleted" event.
34+
*
35+
* @param \App\News $news
36+
* @return void
37+
*/
38+
public function deleted(News $news)
39+
{
40+
Cache::tags(['news', 'latest_news', 'statistics_data', 'tags_cloud'])->flush();
41+
}
42+
}

0 commit comments

Comments
 (0)