Answer the question
In order to leave comments, you need to log in
Where to add Class in Yii 2 so that it always works when rendering any page?
Where to add Class in Yii 2 so that it always works when rendering any page?
Answer the question
In order to leave comments, you need to log in
I usually make BaseController in projects, from which I then expand all the rest.
BaseController.php:
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
class BaseController extends Controller
{
public function init()
{
//some
}
}
<?php
namespace frontend\controllers;
use Yii;
class SiteController extends BaseController
{
public function actionIndex()
{
return $this->render('index');
}
}
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
class BaseController extends Controller
{
public $userid;
public function init()
{
$this->userid = Yii::$app->user->identity->id;
}
}
Create your class wherever you like, and deduce through the bonds where you need it, the class can store variables and functions that you can use all the time. If namespace and use are correct, everything will work.
---
For example, variables are created like this:
<?php
namespace app\backend\models; // у вас будет свой путь, создайте класс на IDE, чтобы правильно вывести
use Yii; // если используете узы, пишите после namespace
use yii\helpers\Html; // могут понадобится любые классы
class Yourclass {
const CLOCK = '<i class="fa fa-clock-o"></i>'; // только так передаются "переменные"
// в функции self::CLOCK
// во вьюшке, на любой странице Yourclass::CLOCK;
//
public function getTimeName($params = '')
{
// данная функция позволяет выводить оформленную дату с тегами
// в определённом формате, на всём сайте, если вы измените эту функцию
// везде где вы выведите этот формат поменяется одновременно, что удобно
// Yourclass::getTimeName(вставляете ваше значение);
$rezult = Html::tag('small', self::CLOCK . Yourclass::formTime($params), ['class' => 'text-muted']);
return $rezult;
}
}
<?php
use yii\helpers\Html;
use app\backend\models\Yourclass; // я на абум написал, у вас будет свой путь
?>
<?=Yourclass::CLOCK;?> - глиф иконка часов FontAwesome
<?=Yourclass::getTimeName($model->time);?> - дата и\или время в виде html кода в заданном формате
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question