【问题标题】:Reuse Codes In Laravel在 Laravel 中重用代码
【发布时间】:2018-09-02 08:52:50
【问题描述】:

我有一些

如果(){

} 否则 {

}

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

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

【问题讨论】:

  • 你得再解释一下你的问题

标签: laravel oop reusability code-reuse


【解决方案1】:

你可以简单地将这个 sn-p 放入一个函数中,比如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:如果你不想暴露你的源代码,我可以删除部分代码,只留下解释

【讨论】:

    猜你喜欢
    • 2016-02-11
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2018-05-30
    • 2016-07-24
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多