更新时间:2023-02-26 07:38:05
解决方案1(Doctrine Listener / Subscriber)
监听器/订阅者
命名空间Acme \YourBundle\EventListener;
pre>
使用Doctrine\ORM\Event\LifecycleEventArgs;
使用Acme \YourBundle\Entity\Student;
class RoleListener
{
public function prePersist(LifecycleEventArgs $ args)
{
$ entity = $ args-> getEntity
$ entityManager = $ args-> getEntityManager();
//检查学生,教师,任何...
if($ entity instanceof Student){
$ entity-> addRole('ROLE_WHATEVER');
//或
$ entity-> addGroup('students');
// ...
}
// ...
}
}服务配置
#app / config / config.yml或者在bundle extension中加载
services:
your.role_listener:
class:Acme\YourBundle\EventListener\RoleListener
tags:
- {name:doctrine.event_listener,event:prePersist}解决方案2 (Doctrine LifeCycle Callbacks):
使用生命周期回调,您可以将角色/群组操作直接整合到您的实体中。
/ **
* @ ORM\Entity()
* @ ORM\HasLifecycleCallbacks()
* /
class Student
{
/ **
* @ ORM\PrePersist
* /
public function setCreatedAtValue()
{
$ this-> addRole('ROLE_WHATEVER');
$ this-> addGroup('students');
}