繁体   English   中英

CakePHP控制器自定义功能无法识别

[英]CakePHP controller custom function not recognized

我正在学习CakePHP并遵循教程。

在实现DELETE控件时,我决定创建一个自定义函数以包含一些重复的代码行。 但是,我的自定义函数在尝试调用时无法识别。

我的代码如下:

class PostsController extends AppController{
public $helpers = array('Html', 'Form');

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

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);
}//view

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.'));
            return $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}//add

public function edit($id=null){

    idCheck($id);

    $post = $this->Post->findById($id);
    if(!$post)
        throw new NotFoundException(__('Invalid post'));

    if($this->request->is(array('post', 'put'))){
        $this->Post->id = $id;
        if($this->Post->save($this->request->data)){
            $this->Session->setFlash(__('Your post has been updated!'));
            return $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash(__('Unable to update your post.'));
    }

    if(!$this->request->data)
        $this->request->data = $post;
}//edit

public function delete($id=null){
    idCheck($id);
}

public function idCheck($id=null){
    if(!$id)
        throw new NotFoundException(__('Post ID required'));

    if(!is_numeric($id))
        throw new NotFoundException(__('Post ID must be numeric'));
}
}

我要做的只是调用idCheck()函数,但出现此错误:

错误:调用未定义函数idcheck()

在cakephp中,您不能直接调用函数。

看到您在玩对象,如果要调用属于当前对象的函数,请使用

$this->Your_function();

根据您的问题,使用:

$this->idCheck($id);

这意味着为当前对象调用函数idCheck()函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM