Guest User

Untitled

a guest
Jun 20th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. <?php
  2.  
  3. // create a liveAware trait
  4.  
  5. trait LiveAware
  6. {
  7. public function scopeLive(Builder $builder)
  8. {
  9. return $builder->whereNotNull('live_at');
  10. }
  11.  
  12. public function isLive()
  13. {
  14. return $this->live_at !== null;
  15. }
  16.  
  17. public function isNotLive()
  18. {
  19. // the reason we use this way instead of checking $this->live_at === null
  20. // is if we change the implementation of how to check live. We only need to change code in isLive().
  21. // So it is more maintable
  22. return ! $this->isLive();
  23. }
  24. }
  25.  
  26.  
  27. // in our controller
  28. class ArticleController
  29. {
  30. public function show(Article $article)
  31. {
  32. abort($article->isNotLive(), 404);
  33.  
  34. // ...
  35. }
  36. }
  37.  
  38. // We may wanto use globl scope to tidy things up. But if we create admin pannel, we may want the admin to see the not live
  39. // articles. We may want to add if check in the global scope. Another way is we can create a middleware for thhis
  40.  
  41. class IsLive
  42. {
  43. public function handle(Request $request, Closure $next, $model)
  44. {
  45. if ($request->{$model}->isNotLive())
  46. {
  47. return abort(404);
  48. }
  49.  
  50. return $next($request);
  51.  
  52. }
  53. }
  54.  
  55. // In our Cnotroller, we just need to
  56.  
  57. class ArticlesController
  58. {
  59. public function __construct()
  60. {
  61. // register the middleware as is.live in the kernel
  62. $this->middleware(['is.live:article']);
  63. }
  64.  
  65. public function show(Article $article)
  66. {
  67. // ...
  68. }
  69. }
Add Comment
Please, Sign In to add comment