在 Laravel 中重用代码

Reuse Codes In Laravel

我有一些

if() {

} else {

}

条件,多次使用。我想重复使用它们,而不是一遍又一遍地输入它们。

这是我的控制器源代码:MyController.php

您可以简单地将此代码段放入一个函数中,比如 buildExamData:

protected function buildExamData($examdata) {
    $examIdsNesting = [];

    foreach ($examdata as $examdatum) {
       $examIdsNesting[] = array(
          'Exam Name' => $examdatum->Name,
          'Exam Code' => $examdatum->ExamCode,
          'Exam Details' => $examdatum->Details,
          'Exam Owner' => $examdatum->Owner,
       );
    }
    return $examIdsNesting;
}

然后每次你想执行这个操作时只需调用 buildExamData() 例如:

public function GetListOfExams(Request $request)
{
    //select Name, ExamCode,Details, Owner, from exams where owner = Owner and status = 1;
    $owner = $request->get('owner'); //get this from GET request
    $status = 1; //it is intialized here
    $examdata = Exam::select('Name', 'ExamCode', 'Details', 'Owner')->where(
        array(
            'Owner' =>  $owner,
            'status'=>  $status
        )
    )->get();

    return $examdata->isEmpty()
        ? response()->json('Exam not found for this Owner', 404)
        : response()->json($this->buildExamData($examdata), 200);
 }

Please note that I have made a little refactor to the buildExamData() function so you don't need array_push()

Ps: if you don't want to expose your source code I can delete the portion of the code and just leave the explanations