簡體   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