php - 如何在 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
}
}
解决方案
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.
推荐阅读
- laravel - 使用 Laravel 中的关系根据第二个表中的条件获取关联记录
- reactjs - 在将 React 应用程序转换为 Preact 期间面临的问题
- node.js - 更新多个对象时如何提高 MongoDb 性能
- python - Sympy 表达式的评估不会产生正确的结果
- javascript - 使用JS更改表格中单元格的行颜色
- node.js - 无法从导出的 firebase 函数中引用未导出的 firebase 函数
- android - 以固定的时间间隔更改 Android UI
- xamarin.forms - android.contentResolver 在空对象引用上
- python - Scrapy 没有从 Selenium 解析 page_source
- swiftui - 当列表中有两个项目时,foreach中的Swiftui Navigationlink崩溃