我正在构建一个带有用户身份验证部分的网站,在Symfony 2.1.3上,使用Doctrine 2。每个用户可以是"用户组"的成员,每个用户组可以包含许多用户。
所以这是一个多对多的关系。
我按照安全教程对我的用户进行身份验证,它运行良好。http://symfony.com/doc/current/cookbook/security/entity_provider.html
密码已编码;数据库关系工作正常。
我有一个服务,可以处理"登录成功"事件,并将用户添加到会话中。我认为它工作正常,因为我在我的父前端控制器中找到我的用户属性。
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$session = $request->getSession();
$session->set('_user', $token->getUser());
if ($session->has('referer')) {
if (($session->get('referer') !== null) && ($session->get('referer') !== '')) {
$response = new RedirectResponse($session->get('referer'));
} else {
$response = new RedirectResponse($request->getBaseUrl() . '/');
}
} else {
// if no referer then go to homepage
$response = new RedirectResponse($request->getBaseUrl() . '/');
}
return $response;
}
但是现在,我想获取经过身份验证的当前用户的组,它给了我一个空数组......
// Somewhere in a controller action.
$session = $this->getRequest()->getSession();
$current_user = $session->get('_user');
echo '<pre>';
exit(var_dump($current_user));
object(MeMyProjectCoreBundleEntityUser)#38 (16) {
[...]
["groups":"MeMyProjectCoreBundleEntityUser":private] => object(DoctrineORMPersistentCollection)#34 (9) {
["snapshot":"DoctrineORMPersistentCollection":private] => array(0) {
}
["owner":"DoctrineORMPersistentCollection":private] => NULL
["association":"DoctrineORMPersistentCollection":private] => NULL
["em":"DoctrineORMPersistentCollection":private] => NULL
["backRefFieldName":"DoctrineORMPersistentCollection":private] => NULL
["typeClass":"DoctrineORMPersistentCollection":private] => NULL
["isDirty":"DoctrineORMPersistentCollection":private] => bool(false)
["initialized":"DoctrineORMPersistentCollection":private] => bool(false)
["coll":"DoctrineORMPersistentCollection":private] => object(DoctrineCommonCollectionsArrayCollection)#33 (1) {
["_elements":"DoctrineCommonCollectionsArrayCollection":private] => array(0) {
}
}
}
}
我希望用户根据他的组访问某些功能...所以不得到这些团体对我来说真的很糟糕。知道吗?
我的 yml 模型配置文件:
MeMyProjectCoreBundleEntityUser:
type: entity
repositoryClass: FSBIntranetCoreBundleRepositoryUserRepository
table: users
fields:
id:
id: true
type: integer
unsigned: false
nullable: false
generator:
strategy: IDENTITY
[...]
manyToMany:
groups:
targetEntity: Usergroup
inversedBy: users
joinTable:
name: usergroups_for_user
joinColumns:
user_id:
referencedColumnName: id
inverseJoinColumns:
usergroup_id:
referencedColumnName: id
lifecycleCallbacks: { }
Doctrine 仅在调用函数 getGroups 时加载 ArrayCollection _elements,因为默认情况下,EAGER 模式处于非活动状态。getGroups() 函数的结果是什么?
模式 EAGER (示例 : @ManyToOne(targetEntity="MyModelUserUser", fetch="EAGER")
) 强制 doctrine2 加载所有数据。