且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在成功注册时分配角色?

更新时间:2023-02-26 07:38:05

解决方案1(Doctrine Listener / Subscriber)






您可以轻松地添加一个doctrine prePersist



监听器/订阅者



 命名空间Acme \YourBundle\EventListener; 

使用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');
// ...
}

// ...
}
}
pre>

服务配置

  #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');
}