有没有动态的方法来构建我的数组,以便我不必指定其中的每个键/元素?

时间:2016-11-01 19:40:50

标签: php arrays refactoring

所以我有一个函数可以从几个不同的表中提取数据并将它们放在一个数组中,我可以为日历/议程输出。我的主要问题是,如果/当要求将新项目放置在日历上时,此方法将变成越来越大的怪物。我已经添加了一些重构来实现这么小,但它实在是太大了。

问题:是否有更好的方法来构建我的阵列甚至是一个可以使其在未来干净/易于扩展的对象?是否有一些我可以用来直接帮助我更好地重构这种方法的博客/文章?

private function generateCalendarItems()
{
    //Let's build that calendar.
    $date = $this->start;
    $i = 0;
    $separatedList = $this->separatedList();
    $travelList = $this->travelsList();
    $trainingUsersList = $this->trainingUsersList();
    $newUserList = $this->newUserList();

    while ($date <= $this->end) {
        $currentDate = $date->format('Y-m-d');
        $separatedArray = $this->pushToArray($separatedList, ['destroyed_date'], $currentDate);
        $travelsArray = $this->pushToArray($travelList, ['leave_date', 'return_date'], $currentDate);
        $trainingUsersArray = $this->pushToArray($trainingUsersList, ['due_date'], $currentDate);
        $newUserArray = $this->pushToArray($newUserList, ['created_at'], $currentDate);
        $trainingUsersArray = $this->groupUsersForTraining($trainingUsersArray);

        if ((!empty($separatedArray) || !empty($travelsArray) || !empty($trainingUsersArray) || !empty($newUserArray)) || $currentDate == Carbon::today()->format('Y-m-d')) {
            $this->calendarArray[$i]['date'] = $currentDate;
            $this->calendarArray[$i]['separated'] = $separatedArray;
            $this->calendarArray[$i]['travel'] = $travelsArray;
            $this->calendarArray[$i]['trainingUser'] = $trainingUsersArray;
            $this->calendarArray[$i]['newUser'] = $newUserArray;
        }
        $date->addDay();
        $i++;
    }
}

可以在此处找到完整的Calendar类: https://github.com/scci/security-employee-tracker/blob/master/app/Handlers/Calendar/Calendar.php

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

$this->calendarArray[$i] = array('data' => $currentDate, ...., 'newUser' => $newUserArray);

无法真正摆脱列出每个键/值来构建数组,但至少可以省去你不得不一遍又一遍地写出$this->calendarArray