A global 'use' that serves all views at once

Hi Everyone,

Currently I need to add in every view:

use yii\helpers\ArrayHelper;
use yii\helpers\Url;

Is there a single place I could import/load/use the classes so that they are available in all views?
So that the view knows what is ArrayHelper without prefixing it with full classpath.

In other words - is there a way to use
$dataList=ArrayHelper::map(…
in a view without putting ‘use yii\helpers\ArrayHelper;’ in the same view?

Thank you

Put it in the main template and all views will have access to it.

Thank you for the advice.

I commented out ‘use yii\helpers\ArrayHelper;’ in views/…/_form.php
and added it in views/layouts/main.php

I get “Class ‘ArrayHelper’ not found” then.

I am using yii2-app-basic.
Maybe you meant some other place.

It’s not possible, as far as I know.

It is not possible to avoid adding use. You either have to use full class name all the time or add use statements to the top of your files.

Modern IDEs help with that a lot, which IDE/editor are you using?

I am mistaken, but in my defense : I am using a template engine that does support includes :wink:

there is way around it by using class aliases but I would not recommend it

1 Like

Thank you all for sharing your ideas.

@CeBe: I am not using IDE just a text editor for my small project.

Aliasing the few classes I commonly use can be an accepted solution.
Following @alirz23 advice I added:

class_alias('yii\helpers\ArrayHelper','ArrayHelper');

before ‘return $config;’ in config/web.php and it works.

2 Likes

Hi,
if you are on PHP 7, the use section could be shortened like this:

use yii\helpers\{ArrayHelper, Url, AnyOther, AnyQty};

But be aware that there is no back compatibility with PHP 5 for this.

Regards.