How do I lazy load custom classes located in the components folder

In particular, I have an abstract class that is extended by several sub classes. Each in their own file with the name of the file being the same as the name of the class.

At the moment, the only way I have worked out to access these classes is by including the following wherever I need them.




Yii::import('application.components.myClass.*');

require_once('myClass.php');



Can I lazy load these and access them through Yii::app()-> in some way?

I guess I need to put something in the config, in the components section. But I am not sure what.

Hi,

you can add this path to the import-array in your config.

In main.php:




    'import'=>array(

        // ...

        'application.components.myClass.*',

    ),



and afterwards you can use something like


$myObject = new myClassXY();

and Yii will automatically search in application.components.myClass for a file/class named myClassXY and import it.

Regards

Thanks

Note that this will import the directory components/myClass/*. If you only want your classfile it’s enough to use Yii::import(‘application.components.myClass’);. But that’s probably also obsolete as you already will have Yii::import(‘application.components.*’); in your config.

Sure, you can configure custom application components. It’s best to extend these from CApplicationComponent. Then configure it like this:


    'components'=>array(

        'somename'=>array(

            'class'=>'SomeClass',

            'somepublicvar'=>'configvalue',

        ),



It will be available with Yii::app()->somename and only be instantiated on first access of this property.