在布局中显示各种模型的数据的最佳方法是什么?

时间:2015-02-24 21:34:57

标签: php yii2

在我的布局文件中从各种模型获取数据的最佳方法是什么(main.php在页脚中使用)。例如,我希望我的页脚总是包含来自我的产品模型/表的5条记录。

所以我有两个问题:

  1. 如何在布局/公共组件文件中显示数据?
  2. 当只想要五个记录时,这是在模型函数中还是在我的视图foreach循环中完成的?

4 个答案:

答案 0 :(得分:0)

要在布局文件中显示数据,您必须在Controller范围内有一个变量。所以如果你有类似的东西:

class BookController extends Controller {
   /*
    * The var below will be accessible from your template files (main.php, etc)
    * and any other view file
    */
    public $globalContent = 'Hello';

    public function actionIndex(){
         //The var below is not accessible in your main.php
         $localContent = 'World'; 
         $this->render('index', array('localContent' => $localContent));
    }
}

在所有控制器中使用公共变量的一个好方法是让控制器扩展自定义Controller.php。

有关详细信息,请参阅How do I pass a global variable in Main layout page before $content in Yii2

答案 1 :(得分:0)

您也可以在布局文件中使用它,但我认为这不是一个好方法,数据库事务应该在Model中。

$command = Yii::$app->db->createCommand("select * from product;");
$products = $command->queryOne();

答案 2 :(得分:0)

我做了以下工作。

使用我的common / components文件夹创建一个控制器,其中包含以下代码:

<?php

namespace common\components;

use frontend\models\ProductItem;

class FooterComponent
{
    public static function getProducts()
    {
        return ProductItem::find()->limit(8)->all();
    }
}

然后在我的布局文件(main.php)中

<?php 

foreach(common\components\FooterComponent::getProducts() as $product){
      echo "<li><a href='" . $product->id . "'>" . $product->name . "</a></li>";
  } 

?>

答案 3 :(得分:0)

我以类似的方式解决问题。 遵循本教程 http://www.bsourcecode.com/yiiframework2/how-to-create-custom-widget-in-yii2-0-framework/ 我在$app/components目录中创建了一个小部件,并使用其返回的值以默认布局显示它。