Code organization

Hi,

I wonder where to place some code, according to what it does, I explain:

  • where to put view helpers classes, action helpers classes ?

  • where to put own components ?

  • where to put my own classes, whatever they do ?

When I don’t know where to put something, I put it inside protected/components.

Thanks

It’s completely up to yourself to decide where you put your files, I’ve been keeping a seperate lib directory for my own classes and external libraries I’ve downloaded. You don’t even have to put it in your website’s directory, just register the path in your config.php:


<?php

return array(

  ...

  'aliases'=>array(

    'lib'=>'/path/to/lib',

  ),

  ...

);

I hope this helps you out :)

You are free do create own folders next to components. For example we have a folder protected/lib holding non-components.

Thanks, it helps.

I didn’t know about “aliases” config.

Is it somehow like ‘import’=>array() that allows autoloading ?

With your example, you can then simply instantiate any class wherever you are in the code ?

It’s best to use it together, aliases for defining extra paths and import to load classes etc from there, eg:


<?php

return array(

  ...

  'aliases'=>array(

    'lib'=>'/path/to/lib',

  ),

  ...

  'import'=>array(

    ...

    'lib.*',

  ),

);

Nice, learning every day something new…

Sorry, I don’t understand the goal of defining extra paths.

For me, import seems to be sufficient.

What does "aliases" bring more ?

Well, I think I understand:

  • aliases correspond to a path (‘lib’=>’/path/to/lib’,…)

  • then we can use import with these aliases to allow autoloading : ‘import’=>array(‘lib.*’,…)

We need to define aliases to our own paths before we can use import for those paths.

Correct, that’s how it works.

But… you don’t NEED to do anything, personally I found it useful to seperate my bits of code. If you want you can put everything into protected/lib/ and add each folder to import in your config.php. For example:


...

  'import'=>array(

  ...

  'application.lib.*',

  'application.lib.stuff.*',

  'application.lib.moreStuff.*',

  'application.lib.moreStuff.extraStuff.*',

  ...

  ),

...

I don’t understand why you say “you don’t NEED to do anything”.

Heh, I’m merely implying that mine is one of many solutions. If you prefer to do something else it is all up to you, I would go for the solution above but you might prefer to place everything somewhere else.

Sorry for confusing you :) I just found my solution useful for keeping order.

Ok I understand :) Thanks for the answers !

I come back on this topic for a question about import: I don’t understand that after having used import, I need to user require_once;

Example:

I do this: Yii::import(‘application.vendors.zend.*’);

Then why do I need to do this: require_once(‘Zend/Pdf.php’);

before I can instantiate Zend_Pdf: $pdf = new Zend_Pdf(); ???