Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Passing $this->data to the View from Controller

I'm using CakePHP 1.2 and I'm just wondering if there is any side affect on passing the $this->data to the View from the Controller.

Ex:

// inside PostsController, I have this code:
$this->data['Posts'] = $this->Post->find('all');

instead of :

$posts = $this->Post->find('all');
$this->set(compact('posts'));

// inside the /posts/view, I access it like this:
<?php foreach ($this->data['Posts'] as $post) {....};?> 

By doing this, I skipped the $this->set() from the controller all together. Does this violate any MVC pattern or any security issue that I might have overlook? I saw that using the Auth Component, $this->data contains the [_Token] array.

Thanks

like image 318
Kien Pham Avatar asked Nov 12 '09 18:11

Kien Pham


3 Answers

You need to be aware of the different places that Cake Helpers automagically look for data, since that is were it makes a real difference. The Form Helper will fill in fields automatically based on the contents of $this->data. That's how form data persists when validation fails. OTOH, a <select> elements options array is automatically taken from the pluralized field name,
e.g. $form->select('Model.foo_id') will take its options from $foos if set.

As such, $this->data has its special place and shouldn't be used lightly, just as named variables have their use and shouldn't be ignored. Use both as appropriate. If you don't want to auto-set Form Helper content, set() your variables. IMHO it's also more readable to assign a variable name that hints at the data it contains. All your views operating on $this->data is less clear than one view operating on $foo and another on $bar.

like image 95
deceze Avatar answered Sep 19 '22 13:09

deceze


In CakePHP 2.x you should use $this->request->data instead if plain $this->data, otherwise you might end up getting this error:

Indirect modification of overloaded property View::$data has no effect

like image 27
Lukas LT Avatar answered Sep 21 '22 13:09

Lukas LT


$controller->data is meant for data posted to the control from view file.

$view->data is for general data.

I would avoid doing it to keep myself sane. besides you are typing more in view.

like image 37
Funky Dude Avatar answered Sep 17 '22 13:09

Funky Dude