Home  >  Q&A  >  body text

Build efficient Laravel applications: implement dual API and view functions, and separate controllers

<p>I would like to structure my Laravel application to handle API and view functionality efficiently while avoiding duplication in controllers. </p> <p>How do I set up my application to have two separate controllers, one dedicated to API operations and another for view-related operations? </p> <p>Also, what is the best way to handle the shared logic between these controllers, and how do I ensure the correct separation of concerns? </p>
P粉558478150P粉558478150402 days ago516

reply all(1)I'll reply

  • P粉818125805

    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.

    reply
    0
  • Cancelreply