在Laravel重用代码

时间:2018-03-23 15:54:16

标签: laravel oop reusability code-reuse

我有一些

  

if(){

     

}其他{

     

}

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

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

1 个答案:

答案 0 :(得分:0)

您只需将此代码段放入函数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);
 }
  

请注意,我对buildExamData()功能进行了一些重构,因此您不需要array_push()

     

Ps:如果您不想公开您的源代码,我可以删除代码部分,只留下解释