如何在 CakePHP 中访问某个 GET 数据


How to access a certain GET data in CakePHP?

我目前正在写一本地址书,并首次使用框架(CakePHP)作为MVC。不幸的是,我遇到了一些麻烦。

我想实现以下几点:

如果网址是

/contacts/view/

我想在列表中显示所有联系人。如果在/view/之后给出一个 id,例如

/contacts/view/1

我只想显示ID 为 1 的联系人。(与第一种情况完全不同的视图/设计)

我的联系人控制器.php如下所示

public function view($id = null){
    if(!$this->id){        
        /*
         * Show all users
         */
        $this->set('mode', 'all');
        $this->set('contacts', $this->Contact->find('all'));
    } else {
        /*
         * Show a specific user
         */
        $this->set('mode','single');
        if(!$this->Contact->findByid($id)){
            throw new NotFoundException(__('User not found'));
        } else {
            $this->set('contact', $this->Contact->findByid($id));
        };
    }        
}

但"$this->模式"始终设置为"全部"。如何检查 ID 是否设置?我真的很想避免"丑陋"的 URL 方案,例如 ?id=1

提前感谢!

您的代码只满足 if 部分,而不会满足其他部分。 使用 (!$id)。

$_GET 数据通过 URL 检索。在 CakePHP 中,这意味着它是通过该方法的参数访问的。

我随便挑名字,请关注!如果您在来宾控制器中并发布到注册方法,您将像这样访问它

function register($param1, $param2, $param3){
}

这些参数中的每一个都是 GET 数据,因此 URL 看起来像

www.example.com/guests/param1/param2/param3

所以现在对于你的问题How can I check whether the id is set or not?

有几种可能性。如果要检查 ID 是否存在,可以执行以下操作

$this->Model->set = $param1
if (!$this->Model->exists()) {
    throw new NotFoundException(__('Invalid user'));
}
else{
    //conduct search
}

或者您可以根据是否设置参数进行搜索

if(isset($param1)){ //param1 is set
    $search = $this->Model->find('all','conditions=>array('id' => $param1)));
}
else{
    $search = $this->Model->find('all');
}

你应该只改变条件,而不是像

public function view($id = null){
    $conditions = array();
    $mode = 'all';
    if($id){
        $conditions['Contact.id'] = $id;
        $mode = 'single';
    }
    $contacts = $this->Contact->find('all', array('conditions' => $conditions));
    $this->set(compact('contacts', 'mode'));
}