Whats the best way to display data from various models within a layout

I was wondering what the best way to get data from various display models within my layout file.

For example I want my footer to always contain 5 record from my products model/table.

So I have two questions one How can I display data within a layout/common component file?

Two when only wanting five records would this be done within a model function or in my view foreach loop?

First solution :

Define a class like Utils in components

namespace app\components;

class Utils


  public static function getProducts()


    return app\models\Product::find()->limit(5)->all();



And in your layout :


  <?php foreach(app\components\Utils::getProducts() as $product): ?>



Second solution :

Create app\components\Controller which is extended by all your controllers.

And create in in this class the same function getProducts()

And after in your layout you can access it with

foreach($this->context->getProducts() as $product)

Third solution :

Create a function in app\components\Controller which will return the HTML like this :

public function getProducts()


  return $this->render>Partial('/layouts/_products', ['products' => app\models\Product::find()->limit(5)->all()]);


Layout :


  <?= $this->context->getProducts() ?>


File layouts/products :

<div id="products">

  <?php foreach($products as $product): ?>