views:

1968

answers:

3

Hi all,

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

+1  A: 

$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.

Funky Dude
I agree with Funky Dude - $this->data, where $this is a model, controller, view or other object, I think should be for data posted from a form or read from a record in the db.I think your version is far less readable and goes against the convention that everyone else is used to, making it far less portable.But if you really want to save a line:$this->set('posts', $this->Post->find('all'));
neilcrookes
+2  A: 

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.

deceze
A: 

There is no good reason for setting $this->data directly except when working with forms.

Why break convention - Controller:set is there for a reason. If you want to pass data to the view for display or display logic purposes you should use the function provided instead of trying to co-opt Controller:data for unintended purposes.

Everything is easier from within CakePHP if you follow the rules and do things the expected, correct way.

Abba Bryant