Import a custom Class in Yii Project

Hello,

I am currently porting a vanilla php project to a yii project.
I’ve now come to the point where I want to import my own class into Yii. I would like to be able to use this class and its methods in several controllers.

I used this guide.

I placed my class in the folder rootdir/vendor/myClass/myClass.php.

I have adjusted the class as follows:

namespace app\vendor\MyClass;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
 
class MyClass extends Component {
...
}

I also added my component to the web.php file.
‘components’ => [
‘MyClass’ => [
‘class’ => ‘app\vendor\MyClass’,
],

At the end i inserted this line in my controller:
use app\vendor\MyClass;

But when i want to use the class in a controller i get an error.

$myObject = new MyClass(1,2,3);

Class ‘app\vendor\MyClass’ not found

What have I done wrong?

I played around a little with the namespaces but that wasn’t the solution either

Solution:

i figured it out. i have to change the use statement to “use app\vendor\MyClass\MyClass”

Hi, good that you could solve your problem. :slight_smile:

… but just some advice …
Unless it is a package which can be managed via package manager (composer)…

  1. do not manually place any code inside the vendor directory.
  2. never manually change any code inside the vendor directory.
  3. content of the vendor directory will not be pushed to any git remotes.

Instead follow the mentioned guide and place your class in a path like app/components/

Best regards

2 Likes

thanks for the hint! :slight_smile: