views:

695

answers:

4

What is the best way to name variables which contain multiple words? After going through lots of projects available in the CakePHP forge, I have noticed people use either camelCase, underscores or camelCase for variables and underscores for data sent to the view.

An example of the last one would be:

$activeSites = $this->Site->find('all',array('conditions'=>array('Site.active' => '1'), 'recursive' => -1));
$this->controller->set('active_sites', activeSites);
+5  A: 

As most people will tell you, there is not "best way" to name variables, other than to be consistent. Decide the naming convention you like the most, and stick to it. If you're continuing on a project, keep the naming convention that is already there. That is all the advice I can give you.

Blixt
A: 

Usually you use underscores and only lower case/upper case for labels that are case insensitive. When passed around they may be handled in a case sensitive way.

Case insensitive examples:

  • GET/POST attributes - but on server side they may be handled in a case sensitive way
  • urls - but on server side they may be handled in a case sensitive way
  • filenames on windows - but when transferred to a *nix system they are case sensitive
Mercer Traieste
+1  A: 

There isn't a right or wrong answer to this. I usually name it:

$active_sites = $this->Site->find('all',array('conditions'=>array('Site.active' => '1'), 'recursive' => -1));
$this->controller->set('active_sites', $active_sites);

I think any way is fine, but your example showed that the variable in the view and the controller isn't the same. That can be avoided by adopting $active_sites or $activeSites throughout.

(Actually after a while, I start using underscores everywhere.)

KahWee Teng
+3  A: 

According to the naming conventions used for CakePHP itself (http://book.cakephp.org/view/509/Coding-Standards#Variables-609), variables are named in the following way:

Normal variables should start with a lowercase letter, and should be written in camelBack in case of multiple words.

dhofstet
Also worth mentioning, core developers feel so strongly about this that it was even enforced at one point for parameters passed with compact()!
dr Hannibal Lecter
also, if you watch carefully, when you pass variables to the view in camelCase form, the form helper loves it and gobbles them up. i can't remember the specifics, so take this example with a pinch of salt: if you have a dropdown in your view created like so "$form->input('venue_type', array('type' => 'select'))", if you pass a variable called $venueTypes (or similar) the form helper will automatically use this as the $options array for that field. :)
deizel