Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 847
intumwa Avatar asked Jul 27 '15 11:07

intumwa


People also ask

How to update composer in Yii2?

You can update Composer by running composer self-update . The first command installs the composer asset plugin which allows managing bower and npm package dependencies through Composer. You only need to run this command once for all. The second command installs Yii in a directory named basic .

What are behaviors in Yii?

Behaviors are instances of yii\base\Behavior, or of a child class. Behaviors, also known as mixins, allow you to enhance the functionality of an existing component class without needing to change the class's inheritance.


1 Answers

Easily you can create a component:

<?php

namespace frontend\components;

use yii\base\Component;

class MyComponent extends Component
{
    public function hello()
    {
        return "Hello, World!";
    }
}

Register it as a component in your frontend/config/main.php file:

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    // Some code goes here
    'components' => [
        // some code here
        'memem' => [
            'class' => 'frontend\components\MyComponent'
        ],
    ],
];

and finally use it where you need:

<?php

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\widgets\Breadcrumbs;
?>
<?php $this->beginPage()?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="<?=Yii::$app->charset?>">
  <meta name="usage" value="<?=Yii::$app->memem->hello()?>">
like image 50
meysam Avatar answered Oct 28 '22 11:10

meysam