简体   繁体   中英

CakePHP controller custom function not recognized

I'm learning CakePHP and following this tutorial.

In implementing the DELETE control, I decided to create a custom function to contain some duplicating lines of code. However, my custom function is not recognized when I attempt to call it.

My code is as follows:

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'));
}
}

All I'm trying to do is call my idCheck() function but I get this error:

Error: Call to undefined function idcheck()

in cakephp you cant call functions directly.

See you play with object ,and if you want to call function that belongs to current object , use

$this->Your_function();

According to your question,use:

$this->idCheck($id);

It means call function idCheck() function for current object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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