我实际上遇到了类似的困惑,但是其他答案没有帮助,并且 Phalcon 的官方文档没有找到正确的方法,所以如果您使用的是 Micro,很难找到有效的答案在网上。所以我之前用自己的反思来了解Phalcon的,最后得出以下答案,希望对你有所帮助。祝你好运!
<?php
$eventsManager = new \Phalcon\Events\Manager();
$eventsManager->attach(
'micro:beforeExecuteRoute',
function (\Phalcon\Events\Event $event, $app) {
$controllerName = $event->getSource()->getActiveHandler()[0]->getDefinition();
$actionName = $event->getSource()->getActiveHandler()[1];
}
);
$app = new \Phalcon\Mvc\Micro($di);
$app->setEventsManager($eventsManager);
如果你想用 before 事件实现 ACL,下面的 AclAnnotation 代码可能会有所帮助:
<?php
class AclAnnotation
{
protected $private = true;
protected $roles = [];
protected $component = [];
protected $access = [];
public function __construct($event, $app)
{
$controllerName = $event->getSource()->getActiveHandler()[0]->getDefinition();
$actionName = $event->getSource()->getActiveHandler()[1];
$reflector = $app->annotations->get($controllerName);
$annotations = $reflector->getClassAnnotations();
if (!$annotations) {
throw new ErrorException('The permission configuration is abnormal. Please check the resource permission comments.');
return;
}
if (
$annotations->has('Private')
&& ($annotation = $annotations->get('Private'))->numberArguments() > 0
) {
$this->private = $annotation->getArguments('Private')[0];
}
if (
$annotations->has('Roles')
&& ($annotation = $annotations->get('Roles'))->numberArguments() > 0
) {
$this->roles = $annotation->getArguments('Roles');
}
if (
$annotations->has('Components')
&& ($annotation = $annotations->get('Components'))->numberArguments() > 0
) {
$this->components = $annotation->getArguments('Components');
}
$annotations = $app->annotations->getMethod($controllerName, $actionName);
if (
$annotations->has('Access')
&& ($annotation = $annotations->get('Access'))->numberArguments() > 0
) {
$this->access = $annotation->getArguments('Access');
}
}
public function isPrivate()
{
return $this->private;
}
public function getRoles()
{
return $this->roles;
}
public function getComponents()
{
return $this->components;
}
public function getAccess()
{
return $this->access;
}
}
在 index.php 中创建事件监听器:
<?php
$eventsManager = new \Phalcon\Events\Manager();
$eventsManager->attach(
'micro:beforeExecuteRoute',
function (\Phalcon\Events\Event $event, $app) {
$aclAnnotation = new AclAnnotation($event, $app);
if (!$aclAnnotation->isPrivate()) {
return true;
}
$acl = $app->currentACL;
// Verify that you have access permission for the interface
if (!$acl->isAllowed($aclAnnotation->getRoles(), $aclAnnotation->getComponents(), $aclAnnotation->getAccess())) {
throw new \ErrorException('You do not have access to the resource', 40001);
return false;
}
return true;
}
);
$app = new \Phalcon\Mvc\Micro($di);
$app->setEventsManager($eventsManager);
关于注解的使用,可以参考这里:
https://docs.phalcon.io/5.0/en/annotations