Import General Classes

In Yii 1.1 I used to import a few classes that I use almost everywhere in my application.

In main.php at config dir I used to write:

// autoloading model and component classes


'import'=>array(


	'application.models.*',


	'application.components.*',


	'application.myclasses.*',





),

How can I do it in Yii2?

Thank you.

The Guide

To make long story short: namespace your classes correctly and they will be autoloaded.

For example if you are using basic template ( and the name of your application is "basic" ) you can create myclasses folder in the root of application (basic/myclasses). And all classes you put there namespace with


namespace app\myclasses;

They will be autoloaded. To use your common class somewhere you would just use it like this:


use app\myclasses\MyCommonClass;

NOTE: If you are using advanced template app is not your root namespace. You have frontend, backend, common, console…

Sorry! But i’m strugling with this for hours…

My code goes like this:

in a view:




use skate_in\skeyra\biblioteca\utils;

$path=utils::lookup("sys_parametros","id",48,"valor");



This view is located at /home/skate_in/views/site

The utils.php file with the class goes like:




namespace skate_in\skeyra\biblioteca;


class utils

{

public static function lookup($tabela,$coluna_pesquisa,$valor_a_pesquisar,$coluna_resultado){


......



utils.php is located at /home/skate_in/skeyra/biblioteca/utils.php

Also, (don’t know if it has some influence) my public files (content of basic/web) is at /home/public_html/skate (this is where user lands on my page)

Yii starts file. But class utils is never recognized…

Can you pls tell me what’s wrong?

Got it!

app means really "app" not the name of your app.

How tipsy of me…

Hi,

in case of advanced yii application. I create a directory in backend

backend\myHelpers; in which there are helpers classes

I namespace then backend\myHelpers;

But I get an Exception

do you know why ? Do we have to make a composer dumpautoload or something else ?

Thks

Can you tell me what exception? And what are you doing that is causing it ? I am not prophet.

yii\base\ErrorException

because yii doesn’t about the class location

Call to undefined function backend\controllers\MyClass()

corrected

was a mistake in namespacing

thx