wt75
(wt75)
October 9, 2018, 11:15am
1
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
jacmoe
(Jacob Moen)
October 9, 2018, 12:22pm
2
Put it in the main template and all views will have access to it.
wt75
(wt75)
October 9, 2018, 1:10pm
3
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.
samdark
(Alexander Makarov)
October 9, 2018, 1:12pm
4
It’s not possible, as far as I know.
CeBe
October 9, 2018, 9:57pm
5
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?
jacmoe
(Jacob Moen)
October 10, 2018, 12:22am
6
I am mistaken, but in my defense : I am using a template engine that does support includes
alirz23
(Alirz23)
October 10, 2018, 4:47am
7
there is way around it by using class aliases but I would not recommend it
1 Like
wt75
(wt75)
October 10, 2018, 1:06pm
8
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
Jay_69
(Biz)
October 13, 2018, 8:47pm
9
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.