Cakephp 3.x 重定向不能在同一控制器中使用同一功能中的另一种方法工作

Cakephp 3.x redirect not working in the same controller using another method in same function

我正在使用 cakephp 3.x 并且我在我的控制器中有一个 edit 函数,我在其中检查 id是否在查询字符串中以及它是否存在于数据库记录中。下面是我的代码,运行良好。

UsersController.php

public function edit($id = null)    
{

    // first checking whether id sent or not .. 
    if(empty($this->request->params['pass']))
    {
        $this->Flash->error('Invalid Action');
        return $this->redirect(['action' => 'index']);
    }        


    // Now checking whether this user id exists or 

    $check_user = $this->Users
                    ->find()
                    ->where(['user_id' => $id])
                    ->toArray();
    if(!$check_user)
    {
         $this->Flash->error('Invalid Id, User not found');
        return $this->redirect(['action' => 'index']);
    }

    $user = $this->Users->get($id); 

    // And so on 
 }

事实是,我在许多其他函数中使用相同的代码来检查相同的事情,所以我想出了在同一个控制器中创建一个通用函数并将其用于多个函数,如下所示。

UsersController.php (已更新)

public function checkId($id)
{
    // first checking whether id sent or not .. 
    if(empty($this->request->params['pass']))
    {
        $this->Flash->error('Invalid Action');
        return $this->redirect(['action' => 'index']);
    }        


    // Now checking whether this user id exists or 

    $check_user = $this->Users
                    ->find()
                    ->where(['user_id' => $id])
                    ->toArray();
    if(!$check_user)
    {
         $this->Flash->error('Invalid Id, User not found');
        return $this->redirect(['action' => 'index']);
    }
}

public function edit($id = null)    
{
    $this->checkId($id);
}

现在,如果我在我的浏览器中执行 url http://localhost/5p_group/users/edit/,我会收到此错误提示 Record not found in table "users" 主键 [NULL]

有人可以指导我如何使用我在上面创建的通用函数来满足这两个条件(检查 url 中的 ID 以及它是否有效)..它是如果我将该代码放入相同的 edit() 函数中,则工作绝对正常。

我们将不胜感激任何帮助或建议。

谢谢

在您的代码中您忘记添加函数参数 $id,您已在查询中使用它

public function checkId()

改为

public function checkId($id)

[更新]

这里还有一个函数return问题

if(empty($id))
{
    $this->Flash->error('Invalid Action');
    return $this->redirect(['action' => 'index']);
}

改为>>

if(empty($id))
{
    $this->Flash->error('Invalid Action');
    $this->response = $this->redirect(['action' => 'index']) ;
    $this->response->send () ;
    die () ;
}