DoLog.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Libs;
  3. use Carbon\Carbon;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\DB;
  6. class DoLog
  7. {
  8. protected $name;
  9. protected $modelOrDb;
  10. /**
  11. * @var \App\Http\Models\User
  12. */
  13. protected $user;
  14. protected $on;
  15. protected $log;
  16. protected $addition;
  17. public function __construct($name = null)
  18. {
  19. $this->name = $name ?? 'default';
  20. return $this;
  21. }
  22. //使用哪个模型或数据库名记录
  23. public function use($modelOrDb)
  24. {
  25. $this->modelOrDb = $modelOrDb;
  26. return $this;
  27. }
  28. // 多数为user
  29. public function by($user)
  30. {
  31. $this->user = $user;
  32. return $this;
  33. }
  34. public function with($addition)
  35. {
  36. $this->addition = $addition;
  37. return $this;
  38. }
  39. //记录
  40. public function log(string $content = '')
  41. {
  42. if ($this->modelOrDb instanceof Model) {
  43. $object = new $this->modelOrDb;
  44. } else {
  45. $object = DB::table($this->modelOrDb);
  46. }
  47. return $object->insert(
  48. [
  49. 'name' => $this->name,
  50. 'content' => $content,
  51. 'addition' => $this->addition ?? '',
  52. 'operator_id' => empty($this->user) ? null : $this->user->getKey(),
  53. 'operator_name' => empty($this->user) ? null : $this->user->username(),
  54. 'created_at' => Carbon::now()->toDateTimeString(),
  55. 'updated_at' => Carbon::now()->toDateTimeString()
  56. ]
  57. );
  58. }
  59. }