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.
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 .
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.
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()?>">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With