我正在运行CakePHP 2.4.1和PHP 5.5.3。
我读了here关于如何创建/写入/访问全局变量的内容,但它对我不起作用。我正在做这样的事情:
class SploopsController extends AppController {
public $crung;
public function process() {
$this->crung = 'zax';
}
public function download() {
$this->response->body($this->crung);
$this->response->type('text/plain');
$this->response->download('results.txt');
return $this->response;
}
}
但下载的文件results.txt
为空,即$this->crung
为空。 (如果我用$this->crung
之类的简单字符串替换'Granjo'
,它就会按预期工作。)有没有人知道出了什么问题?
此外,Configure :: write和Configure :: read对我来说也不起作用(如果我在Controller的一个函数中调用它们的话)。
这是上下文:我在process()中创建一个包含查询结果的数组,并在process.ctp中显示它们,我希望有一个按钮可以将这些结果下载到一个更友好的文本文件中格式。所以我想创建一个全局数组,我可以在process()中修改然后在download()中访问。
谢谢!
答案 0 :(得分:1)
在设置
之前调用procees
public function download() {
$this->process();
$this->response->body($this->crung);
$this->response->type('text/plain');
$this->response->download('results.txt');
return $this->response;
}
修改强>
public function process() {
if (!empty($this->request->data)) { // assuming you're processing the user entered data by means of post
$this->Session->write('crung', 'zax');
$this->Session->write('data', $this->request->data);
}
}
public function download() {
$this->crung = $this->Session->read('crung');
$data = $this->Session->read('data'); // you can process the data in the way you want.
$this->response->body($this->crung);
$this->response->type('text/plain');
$this->response->download('results.txt');
return $this->response;
}
答案 1 :(得分:0)
您需要在使用process()
之前调用$this->crung
功能,如下所示
public function process() {
$this->crung = 'zax';
}
public function download() {
$this->process();
$this->response->body($this->crung);
$this->response->type('text/plain');
$this->response->download('results.txt');
return $this->response;
}
否则您可以使用将在beforeFilter()
函数之前调用的download()
函数。当您需要指定值
public function beforeFilter()
{
$this->crung = 'zax';
}