首页 > 解决方案 > 如何在 cakePHP 3.6 中通过一些条件检查来限制或访问控制器的所有功能

问题描述

我想通过检查 cakephp 3.6 中的某些条件来限制或访问控制器内的所有功能。假设我add(), edit(), view($id)PostController.php. 现在我有一个输入字段,用户将在其中输入一个唯一的 ID。如果数据库中存在此 ID,那么我想授予对这些功能的访问权限。Oterwise 它应该向用户显示一条消息。
我是 cakePHP 的新手,所以我对 cakePHP 不太了解。我尝试过使用 beforeFilter。但它不起作用。

这是我尝试过的代码。现在我没有检查数据库。只需检查输入字段中是否给出了代码。

public function beforeFilter(Event $event)
{
    if(!empty($event->subject()->request->data)){

        return true;
    }
    else{
        return false;
    }
}

我知道也许那些不合适。但我没有得到正确的想法,甚至没有正确的文档。

这是我的控制器代码结构。

use App\Controller\AppController;
use Cake\Event\Event;

class CodesController extends AppController
{

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
}

public function beforeFilter(Event $event)
{
    if(!empty($event->subject()->request->data)){

        return true;
    }
    else{
        return false;
    }
}

public function add()
{
    //code will be here
}
public function view($id)
{
    //code will be here
}
}

标签: phpcakephp

解决方案


Instead of return true from your beforeFilter, use:

$this->Auth->allow(['add', 'edit', 'view']);

No need to do anything in the false case.

Alternately, if those are your only functions, you can simplify to:

$this->Auth->allow();

More details in the manual.


推荐阅读