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
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
.
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
$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.
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.
In cakephp
version 2.*, error occurs when you try to set data on $this->data
精彩评论