mercoledì 10 ottobre 2012

$this->set(compact()) in cakephp too magic hurts

Just discovered that $this->set(compact()) in cakephp 1.3 has a strange behaviour.

a variable with an underscore in it will be available in the view as a camelized rewritten version of the variable...

my_var becomes myVar

too magic hurts!!!

snippet from
archive.robwilkerson.org/2008/12/28/cakephp-watch-out-for-the-compact-function/index.html
(available through google cache)

public function index() {
   …
   $vendor_type      = ‘Food’;
   $application_type = ‘Commercial’;
   $states           = $this->Vendor->Address->State->find ( 
      ‘list’, 
      array ( ‘order’ => ‘State.title’ ) 
   );

   $this->set ( compact ( ‘vendor_type’, ‘application_type’, ‘states’ ) );
   …
}
That’s a little better, but there’s a caveat.
Using this example, I went to my view code and tried to access my $vendor_type variable only to get an undefined variable error. After working my way through various debugging techniques, I pulled out the big gun. In my view, I dumped the output of PHP’s get_defined_vars() function and found that my $vendor_type variable had been renamed to $vendorType. I don’t know if the change was made by CakePHP or by PHP itself, but I didn’t expect it (nor do I have any reason to believe that I should have expected it) and the difference is as fatal to an application as it is obvious.

Nessun commento:

Posta un commento