BlogViewComposer.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. // app/View/Composers/BlogViewComposer.php
  3. // 自动向所有 blog.* 视图注入右边栏数据。
  4. // 在 AppServiceProvider 的 boot() 方法中注册:
  5. //
  6. // use App\View\Composers\BlogViewComposer;
  7. // View::composer('blog.*', BlogViewComposer::class);
  8. // View::composer('layouts.blog', BlogViewComposer::class);
  9. //
  10. // 注意:layouts.blog 也需要注册,否则布局文件拿不到数据。
  11. namespace App\View\Composers;
  12. use Illuminate\View\View;
  13. class BlogViewComposer
  14. {
  15. public function compose(View $view): void
  16. {
  17. $data = $view->getData();
  18. // $user 由各 Controller 方法传入,Composer 不覆盖
  19. $user = $data['user'] ?? null;
  20. if (!$user) {
  21. return;
  22. }
  23. $userName = $user['userName'] ?? null;
  24. if (!$userName) {
  25. return;
  26. }
  27. // 避免重复查询:如果已有数据则跳过
  28. if ($view->offsetExists('categories') && $view->offsetExists('archives')) {
  29. return;
  30. }
  31. // 以下查询根据你的实际 Service/Model 替换
  32. // 示例结构,保持与 BlogController 现有数据结构一致
  33. // Categories:[['id' => ..., 'label' => ...], ...]
  34. if (!$view->offsetExists('categories')) {
  35. $view->with('categories', $this->getCategories($userName));
  36. }
  37. // Tags:[['name' => ...], ...]
  38. if (!$view->offsetExists('tags')) {
  39. $view->with('tags', $this->getTags($userName));
  40. }
  41. // Archives:[['year' => ..., 'count' => ...], ...]
  42. if (!$view->offsetExists('archives')) {
  43. $view->with('archives', $this->getArchives($userName));
  44. }
  45. }
  46. protected function getCategories(string $userName): array
  47. {
  48. // 替换为你的实际查询
  49. // 例:return BlogService::getCategories($userName);
  50. return [
  51. ['id' => 'dharma', 'label' => '佛法'],
  52. ['id' => 'vinaya', 'label' => '戒律'],
  53. ['id' => 'pali', 'label' => '巴利文'],
  54. ['id' => 'practice', 'label' => '禅修'],
  55. ];
  56. }
  57. protected function getTags(string $userName): array
  58. {
  59. // 替换为你的实际查询
  60. return [
  61. ['name' => 'Pāli'],
  62. ['name' => 'Vinaya'],
  63. ['name' => 'Sutta'],
  64. ['name' => 'Abhidhamma'],
  65. ['name' => '三藏'],
  66. ['name' => '注释'],
  67. ];
  68. }
  69. protected function getArchives(string $userName): array
  70. {
  71. // 替换为你的实际查询
  72. // 返回格式:[['year' => 2024, 'count' => 12], ...]
  73. return [['year' => 2024, 'count' => 12]];
  74. }
  75. }