1

我的会话有什么问题?为什么不是对象?我正在尝试cakePHP 快速入门博客示例。我已经复制了所有代码,但是在编辑、删除或添加博客消息时,我无法避免出现此错误:

在非对象上调用成员函数 setFlash()

我在视图中添加了调试行以查看会话变量,并且会话数据看起来很好。我还在控制器中添加了“会话”助手,看看是否有帮助。

控制器:

class PostsController extends AppController {

public $helpers = array('Html', 'Form','Session');

public function index() {
     $this->set('posts', $this->Post->find('all'));
}

public function view($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }
    $post = $this->Post->findById($id);
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }
    $this->set('post', $post);
}

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to add your post.');
        }
    }
}
public function edit($id = null) {
    if (!$id) {
    throw new NotFoundException(__('Invalid post'));
    }
    $post = $this->Post->findById($id);
    if (!$post) {
    throw new NotFoundException(__('Invalid post'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
    $this->Post->id = $id;
    if ($this->Post->save($this->request->data)) {
        $this->Session->setFlash('Your post has been updated.');
        $this->redirect(array('action' => 'index'));
    } else {
        $this->Session->setFlash('Unable to update your post.');
    }
    }
    if (!$this->request->data) {
    $this->request->data = $post;
    }
}

 public function delete($id) {
    if ($this->request->is('get')) {
    throw new MethodNotAllowedException();
    }
    if ($this->Post->delete($id)) {
    $this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
    $this->redirect(array('action' => 'index'));
    }
}
}
?>

我已经向助手添加了“会话”,并且我尝试使用 $this->Session->flash() 但似乎从来没有会话对象。会话正确启动并且会话数据存在:

数组([配置] => 数组([userAgent] => fd7f6d79160a3f20a706f3fed20eff02 [时间] => 1369643237 [倒计时] => 10))

我不知道为什么没有可用的会话实例。

4

1 回答 1

3

您缺少会话组件。

您需要将其添加到您的PostsController

class PostsController extends AppController {
    public $components = array('Session');
    //...
}
于 2013-05-27T04:41:18.793 回答