Задать вопрос
@seddi

Как упростить функции контроллера?

В контроллере вот такая сборка, как упростить, в модель переносить или здесь отдельные функции добавить?

/**
     * view Month
     */
    public function actionMonth()
    {
        $month = date('n', $_GET['time']); // с 1 месяца по 12
        $year = date('Y', $_GET['time']); // 2011

        $customers = Sheel::find()
            ->onCondition('date_execution >= :time1 AND date_execution < :time2')
            ->params([
                ':time1' => ($firstDay = date("Y-m-d", mktime(0, 0, 0, $month, 1, $year))),
                ':time2' => date("Y-m-d", mktime(0, 0, 0, $month + 1, 1, $year)),
            ])
            ->orderBy('date_execution DESC')
            ->joinWith('recipies')
            ->with('company')
            ->all();
        $res = [];
        foreach ($customers as &$item) {
            $res[] = [
                'id_sheel'=>$item->id_sheel,
                'parent_recipies'=>$item->parent_recipies,
                'id_company'=>$item->company->id_company,
                'name_company' => $item->company->name_company,
                'address' => $item->address,
                'recipies' =>
                    $item->recipies->porous_recipies . " " .
                    $item->recipies->size_min . " " .
                    $item->recipies->type_recipies . " " .
                    $item->recipies->brand_recipies . " " .
                    "№ " . $item->recipies->number_recipies,
                'amount_sheel' => $item->amount_sheel,
                'date_execution' => $item->date_execution,
            ];
        }
        $result =new ArrayDataProvider(['allModels' => $res]);

        return $this->render('month', [
            'result' => $result,
            'firstDay' => $firstDay,

        ]);

    }


    /**
     * view Company
     */
    public function actionCompany() 
    {
        $company =$_GET['company']; // с 1 месяца по 12
        $month = date('n', $_GET['time']); // с 1 месяца по 12
        $year = date('Y', $_GET['time']); // 2011
        $customers = Sheel::find()
            ->onCondition('parent_company = :name AND date_execution >= :time1 AND date_execution < :time2')
            ->orderBy('date_execution DESC')
            ->params([
                    ':name' => $company,
                    ':time1' => ($firstDay = date("Y-m-d", mktime(0,0,0,$month,1,$year))),
                    ':time2' => date("Y-m-d", mktime(0,0,0,$month+1,1,$year)),
            ])
            ->orderBy('date_execution DESC')
            ->joinWith('recipies')
            ->with('company')
            ->all();
        $res = [];
        foreach ($customers as &$item) {
            $res[] = [
                'id_sheel'=>$item->id_sheel,
                'parent_recipies'=>$item->parent_recipies,
                'id_company'=>$item->company->id_company,
                'name_company' => $item->company->name_company,
                'address' => $item->address,
                'recipies' =>
                    $item->recipies->porous_recipies . " " .
                    $item->recipies->size_min . " " .
                    $item->recipies->type_recipies . " " .
                    $item->recipies->brand_recipies . " " .
                    "№ " . $item->recipies->number_recipies,
                'amount_sheel' => $item->amount_sheel,
                'date_execution' => $item->date_execution,
            ];
        }
        $result =new ArrayDataProvider(['allModels' => $res]);

        //  VarDumper::dump($res);
        return $this->render('company', [
           // 'materials' => $materials,
            'company' => $company,
            'result' => $result,
            'firstDay' => $firstDay,

        ]);

    }
    /**
* 
* view Address
*/
public function actionAddress()
{ 
    $company =$_GET['id']; 
    $addreses =  Sheel::findAll(['id_sheel' => $company]);
    foreach ($addreses as $key=>$one){
     $addres =$one->address;
            };
     $month = date('n', $_GET['time']); // с 1 месяца по 12
    $year = date('Y', $_GET['time']); // 2011
        $customers = Sheel::find()
            ->onCondition('address = :name AND date_execution >= :time1 AND date_execution < :time2')
            ->orderBy('date_execution DESC')
            ->params([
                            ':name' => $addres,
                            ':time1' => ($firstDay = date("Y-m-d", mktime(0,0,0,$month,1,$year))),
                            ':time2' => date("Y-m-d", mktime(0,0,0,$month+1,1,$year)),
            ])
            ->orderBy('date_execution DESC')
            ->joinWith('recipies')
            ->with('company')
            ->all();
        $res = [];
        foreach ($customers as &$item) {
            $res[] = [
                'id_sheel'=>$item->id_sheel,
                'id_company'=>$item->company->id_company,
                'name_company' => $item->company->name_company,
                'recipies' =>
                    $item->recipies->porous_recipies . " " .
                    $item->recipies->size_min . " " .
                    $item->recipies->type_recipies . " " .
                    $item->recipies->brand_recipies . " " .
                    "№ " . $item->recipies->number_recipies,
                'amount_sheel' => $item->amount_sheel,
                'date_execution' => $item->date_execution,
            ];
        }
        $result =new ArrayDataProvider(['allModels' => $res]);

    return $this->render('address', [
        'result' => $result,
        'firstDay' => $firstDay,

    ]);

}
  • Вопрос задан
  • 207 просмотров
Подписаться 1 Оценить 2 комментария
Решения вопроса 1
@dimabdc
Можно (и нужно) выделять одинаковые куски кода в отдельные функции:
/**
     * view Month
     */
    public function actionMonth()
    {
        $rangeData = $this->_getDateRange();

        return $this->render('month', [
            'result' => $this->_getSheel(),
            'firstDay' => $rangeData['firstDay'],
        ]);

    }

    /**
     * view Company
     */
    public function actionCompany()
    {
        $company =$_GET['company']; // с 1 месяца по 12
        $rangeData = $this->_getDateRange();

        //  VarDumper::dump($res);
        return $this->render('company', [
            // 'materials' => $materials,
            'company' => $company,
            'result' => $this->_getSheel('parent_company', $company),
            'firstDay' => $rangeData['firstDay'],
        ]);

    }
    
    /**
     *
     * view Address
     */
    public function actionAddress()
    {
        $company =$_GET['id'];
        $addreses =  Sheel::findAll(['id_sheel' => $company]);
        foreach ($addreses as $key=>$one){
            $addres = $one->address;
        };
        $rangeData = $this->_getDateRange();

        return $this->render('address', [
            'result' => $result,
            'firstDay' => $rangeData['firstDay'],
        ]);

    }

    /**
     * Get date range
     * 
     * @return array
     */
    protected function _getDateRange()
    {
        $month = date('n', $_GET['time']); // с 1 месяца по 12
        $year = date('Y', $_GET['time']); // 2011

        return [
            'firstDay' => date("Y-m-d", mktime(0, 0, 0, $month, 1, $year)),
            'lastDay' => date("Y-m-d", mktime(0, 0, 0, $month + 1, 1, $year))
        ];
    }

    /**
     * Get sheel
     * 
     * @param mixed $name
     * @param mixed $value
     * @return ArrayDataProvider
     */
    protected function _getSheel($name = null, $value = null)
    {
        $rangeData = $this->_getDateRange();

        $params = [
            ':time1' => $rangeData['firstDay'],
            ':time2' => $rangeData['lastDay'],
        ];
        $where = 'date_execution >= :time1 AND date_execution < :time2';

        if ($name) {
            $where .= " AND :$name = :name";
            $params[":$name"] = $value;
        }

        $customers = Sheel::find()
            ->andWhere($where, $params)
            ->orderBy('date_execution DESC')
            ->joinWith('recipies')
            ->with('company')
            ->all();
        $res = [];
        foreach ($customers as &$item) {
            $res[] = [
                'id_sheel'=>$item->id_sheel,
                'parent_recipies'=>$item->parent_recipies,
                'id_company'=>$item->company->id_company,
                'name_company' => $item->company->name_company,
                'address' => $item->address,
                'recipies' =>
                    $item->recipies->porous_recipies . " " .
                    $item->recipies->size_min . " " .
                    $item->recipies->type_recipies . " " .
                    $item->recipies->brand_recipies . " " .
                    "№ " . $item->recipies->number_recipies,
                'amount_sheel' => $item->amount_sheel,
                'date_execution' => $item->date_execution,
            ];
        }
        return new ArrayDataProvider(['allModels' => $res]);
    }
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
shakatakas
@shakatakas
So so developer
Не совсем пойму почему ты пишешь sql запрос в ручную, если можно:
Sheel::find()->where([
    'and',
    ['>=', 'date_execution', $rangeData['firstDay']],
    ['<', 'date_execution', $rangeData['lastDay']],
]);


Actions..
public function actionAddress()
    {
        $company =$_GET['id'];
    }
/// 
  /**
     * view Company
     */
    public function actionCompany() 
    {
        $company =$_GET['company'];

в
public function actionAddress($company)

Суть этого я вообще не понял, если тебе нужен один последний или какой либо адрес. Просто сделай запрос с лимитом и сортировкой что бы выбрать нужный адрес.
foreach ($addreses as $key=>$one){
     $addres =$one->address;
            };


Вот это еще.
$res[] = [
                'id_sheel'=>$item->id_sheel,
                'parent_recipies'=>$item->parent_recipies,
                'id_company'=>$item->company->id_company,
                'name_company' => $item->company->name_company,
                'address' => $item->address,
                'recipies' =>
                    $item->recipies->porous_recipies . " " .
                    $item->recipies->size_min . " " .
                    $item->recipies->type_recipies . " " .
                    $item->recipies->brand_recipies . " " .
                    "№ " . $item->recipies->number_recipies,
                'amount_sheel' => $item->amount_sheel,
                'date_execution' => $item->date_execution,
            ];

Это обязательное? Тебе нельзя переделать view под модель?

И скрытые вспомогательные методы в контроллере пиши через private. Можешь так же часть данных вынести в helper. Используй все возможности фреймворка. Смотри еще внимательно у тебя повторяется код "orderBy", или же я чего то не до понял.
->onCondition('address = :name AND date_execution >= :time1 AND date_execution < :time2')
            ->orderBy('date_execution DESC')
            ->params([
                            ':name' => $addres,
                            ':time1' => ($firstDay = date("Y-m-d", mktime(0,0,0,$month,1,$year))),
                            ':time2' => date("Y-m-d", mktime(0,0,0,$month+1,1,$year)),
            ])
            ->orderBy('date_execution DESC')
Ответ написан
@seddi Автор вопроса
dimabdc dimabdc от дельное спасибо, то что надо, так же хотел разбить, потому что еще пару views будет
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы