How to write global functions in Yii2 and access them in any view (not the custom way)

Yii1.1 had a CComponent class that had a CBaseController which was the base class for CController. There was a /protected/components/Controller.php class which enabled any function in that class to be accessed in any view.

Yii2 no longer possess the CComponent class. The Yii2 guide indicates that "Yii 2.0 breaks the CComponent class in 1.1 into two classes: yii\base\Object and yii\base\Component". Does anyone know how to write global functions in Yii2 and them in any view, just like it was in Yii1.1 using /protected/components/Controller.php?

A couple of similar topics discuss custom answers, but I would like to know whether there is an official way of doing that, not the custom way.

If you want to have access to properties or methods in all of your views you could extend your view class. Start by making View.php in your components folder. A sample of a starter file is below:




<?php


    namespace app\components;


    use Yii;


    class View extends \yii\web\View

    {

        public $subTitle;


        public function helloWorld()

        {

            return 'Hello World';

        }

    }



Now modify your config file (Add this text to your components array




         'view' => [

             'class' => 'app\components\View',

         ],



Now you could add this code to any of your views:


<?= $this->helloWorld() ?>