CakePHP 的 $this->data
我有一个应用程序,在每个视图中都加载了表单。我已经相当熟悉 CakePHP 的数组语法,并且经常使用 $this->data 参数。
我爱上了瘦控制器和胖模型,所以我在模型中放置了尽可能多的代码。除非我正在做一些复杂的事情,否则我的大多数控制器方法如下所示:
function some_action() {
$this->set('data', $this->Model->some_action($this->data));
}
然后,在我的模型中,我有一个采用一个参数的方法:
function some_action($this_data = NULL) {
// do some stuff, manipulate the data etc.
$this->create();
if ($this->save($this_data)) {
// return success message here
}
}
我已经过于简化了,但您明白了。
我的问题:我总是将 $this->data 发送到我的模型并用变量 $this_data 捕获它。不过,我想知道这是否是一步太多了? Model 是否继承 $this->data ?如果是这样,我可以将上面的控制器方法更改为:
function some_action() {
$this->set('data', $this->Model->some_action());
}
然后在模型中操作 $this->data 而不是我一直在使用的 $this_data 变量吗?最好的做法是什么?
I have an application the is loaded with forms in every view. I've become rather familiar with CakePHP's array syntax and I use the $this->data parameter a lot.
I fell in love with skinny controllers and fat models, so I put as much code in my models as is possible. Unless I'm doing something complex, most of my controller methods look like this:
function some_action() {
$this->set('data', $this->Model->some_action($this->data));
}
Then, in my Model, I have a method that takes one parameter:
function some_action($this_data = NULL) {
// do some stuff, manipulate the data etc.
$this->create();
if ($this->save($this_data)) {
// return success message here
}
}
I've oversimplified, but you get the idea.
My question: I always send $this->data to my model and catch it with a variable, $this_data. However, I was wondering if this is one step too many? Does the Model inherit $this->data? If so, could I change the above controller method to this:
function some_action() {
$this->set('data', $this->Model->some_action());
}
And then manipulate $this->data in my model instead of the $this_data variable I've been using? What would be the best practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好主意,但不幸的是你必须传递
$this->data
作为参数,因为 cake 中的控制器和模型是从不同的父对象扩展的。所以$this->data< /code> 中的含义不同。在控制器中,
$data
属性用于获取 POST 数据,而它是模型获取数据的容器 模型。我建议您阅读以下源代码app/cake/lib/controller/controller.php
和
app/cake/lib/model/model.php
这会让你更清楚。
Nice idea,but unfortunately you have to pass
$this->data
as a parameter because controller and model in cake are extended from diffrent parent-objects.So$this->data
has diffrent meanings in them.In controller,$data
attribute is for get POST data while it's a container for the model’s fetched data in model.And I suggest you to read the source code inapp/cake/lib/controller/controller.php
and
app/cake/lib/model/model.php
That would make you more clear.
然而你可以做的是:
在你的控制器中
这样,你可以使用 Model::some_action(); 中的 $this->data 访问你的模型数据。
What you can do however is :
In your controller
That way, you can access your model data using $this->data in your Model::some_action();