如何将数据存储在单个文件中并在视图文件中调用它?

时间:2015-09-08 21:31:09

标签: php model-view-controller yii

我有一些代码,我一直在我的网站上的不同页面上重写,所以我不断在每个视图文件上重复编写代码。

我想知道如何更改以下代码,以便我只能在一个文件中包含以下代码。是否可以在视图文件中调用此文件?

if ($model->type == 1) {
    $title = __('Sports');
    $icon_activity = 'icon_set_2_icon-117';
}
if ($model->type == 2) {
    $title = __('Cooking lesson');
    $icon_activity = 'icon_set_1_icon-14';
}
if ($model->type == 3) {
    $title = __('Guided tour');
    $icon_activity = 'icon_set_1_icon-30';
}
if ($model->type == 4) {
    $title = __('Language conversation');
    $icon_activity = 'icon_set_1_icon-20';
}

1 个答案:

答案 0 :(得分:1)

在视图文件中编写逻辑不是一个好习惯。相反,您可以创建一个类并在控制器的操作中调用它。例如,我创建这个类: 的 Tools.php

<?php
class Tools{
    public function initialize($type){
         $title = "";
         $icon_activity = "";
         if ($type == 1) {
             $title = __('Sports');
             $icon_activity = 'icon_set_2_icon-117';
         }
         if ($type == 2) {
             $title = __('Cooking lesson');
             $icon_activity = 'icon_set_1_icon-14';
         }
         if ($type == 3) {
            $title = __('Guided tour');
            $icon_activity = 'icon_set_1_icon-30';
         }
         if ($type == 4) {
            $title = __('Language conversation');
            $icon_activity = 'icon_set_1_icon-20';
         }

        return array("title"=>$title, "icon_activity"=>$icon_activity);

    }
}

现在,在你的行动中你可以这样做:

public function actionTest(){
      ...
      $tools = new Tools();
      $result = $tools->initialize($model->type)
      $this->render("yourViewName", array(
            "title" => $result['title'],
            "icon_activity" => $result['icon_activity']
      ));
}

最后,您可以在视图页面中使用$title$icon_activity