P粉8181258052023-08-17 00:53:13
You can create the same class name both for API and for views. By creating the controller in a different namespace, for example:
// 如果您尝试这样做 php artisan make:controller API/AuthController // 它将创建控制器类以及API文件夹。 Http/Controllers/API/AuthContoller.php
For shared issues, please create the Traits folder in the app, and then create the PHP trait class.
<?php namespace App\Traits; use App\Models\Student; trait StudentTrait { public function listAll() { // 获取学生 $students = Student::all(); return $students; } }
You can use it in a model or controller, using the use keyword.
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Traits\StudentTrait; class AuthController extends Controller { use StudentTrait; // 做你的事情 public function getStudents(){ $strudents = $this->listAll(); return new JsonResponse(['students' => $students, 'msg' => 'success']); } }
For independent issues and structured development, you can create service or repository patterns. For more information, please click.