Importing a file of multiple classes

What’s the proper way to go about loading a file containing multiple classes?

I have a file at extensions/JoesUtils.php that contains numerous small classes of general use. I want to load them once for the whole application. It seems that I can’t use the ‘import’ array in the configuration file because this requires that the file name match the class it’s importing. Yii:import() expects a class name. I can’t even create a dummy JoesUtils class in order to piggyback the other class definitions in.

If I should be using a PHP require for this, where is the recommended place for putting the require? And is there a variable containing the project base path that I can require relative to?

Thanks for your help!

~joe

Just put your file into components folder

Pardon, this will not work. I checked in my class that has being included before and it worked how I expect to. Seems you should place each class in to separate file with the same name and then place the files under components. Or under components/myclasses and add a row to import array:


'import' => array(

        'application.models.*',

        'application.components.*',

        'application.components.myclasses.*',

    ),  

Eek! I didn’t know about being able to wildcard after class name prefixes, but I really would rather not ask the server to load a dozen files of 20-30 lines each for every request. That’s the Java model, but even in Java you can have nested classes, thus loading multiple classes in from one file under a common namespace.

I haven’t worked with PHP namespaces yet. Might there be a solution there?

Thanks for your thoughtful response!

~joe

It would not load all 30 files any time you make any request. The import command just add

correspond folder to PHP include path. Take a look http://www.yiiframework.com/doc/api/1.1/YiiBase#import-detail

Right, but it loads one file for every one of the classes I actually use.

Okay. If you want to, you may reload the CController with init method and include your class file there. You already have components/Controller.php , just add the method:


public function init()

{

    Yii::import('application.components.yourClass', true);

}

In this case yii will load your file only once.

But again, I’m not sure it is good idea, because you need redeclare this method for every module you use. I don’t know how to declare this method on one level up.