almost_done
almost_done

Reputation: 397

Class auto loader Yii2

I created a new directory at root 'components'. Then I put a file 'ClassName.php' into this folder. Declare a namespace namespace components; and the class named ClassName Now I try to use it like

$c = new app\components\ClassName()

But there's an error. It says that Class 'components\ClassName' not found. Where am I missing? I suppose that I should add folder components in include_path or something like that. Please help to understand.

Upvotes: 1

Views: 3252

Answers (4)

onlyme
onlyme

Reputation: 4032

It should be late but I guest my solution may help some one later. I had the same issue and the resolved it the way bellow: If you want to autoload (import) a customer class in your app, you to do:

  • create your class where ever you want e.g in my case, i created common/core/Utilities.php
  • then you have to create an alias (alias is a short cut name you give to your folder path). In my case in create an alias for my folder core (note i should also create an alias for my component folder) e.g

    Yii::setAlias('core', dirname(DIR).'/core');

this snippet i put it in my common/config/boostrap.php file. because yii2 load this file at running time.

  • Now you are ready to use your customize class where ever you want. Just do

    $utilities = new \core\Utilities();

Hopefully this may !!!!!!!

Upvotes: 0

Hamid Mohayeji
Hamid Mohayeji

Reputation: 4275

This is how you can create custom components in Yii2 (basic application)

Create a folder named "components" in the root of your application. Then create a class for your component with proper namespace and extend Component class:

namespace app\components;
use yii\base\Component;

class MyComponent extends Component {

    public function testMethod() {
        return 'test...';
    }
}

Add component inside the config/web.php file:

'components' => [
    // ...
    'mycomponent' => [
        'class' => 'app\components\MyComponent'
    ]
]

Now you can access your component like this:

Yii::$app->mycomponent->testMethod();

Upvotes: 2

almost_done
almost_done

Reputation: 397

I found the solution.

Just add

Yii::setAlias('components', dirname(dirname(\__DIR__)) . '/components');

In className.php:

namespace components;

Then usage:

$c = new components\ClassName();

Upvotes: 2

Zudwa
Zudwa

Reputation: 1400

In ClassName.php:

namespace app\components;

Added

When you create new ClassName instance, don't forget the leading backward slash for namespace (AKA fully qualified namespace), if your current namespace is not global, because in that case namespace will be treated as relative (Like UNIX paths), use:

$c = new \app\components\ClassName();  //If your current namespace is app\controllers or app\models etc.
$c = new app\components\ClassName();  //If your current namespace is global namespace

You can read more about namespaces basics in PHP documentation

Upvotes: 1

Related Questions