我正在构建一个多数据库应用程序,需要根据已登录的用户选择数据库。
因此,将存在用于设置和FOS用户包配置的共享表,但是其余表将基于添加了用户的组在不同的数据库中分配。
我已经设法找到了如何根据子域使用不同连接的教程,但这不适用于我的情况。
如何归档?
答案 0 :(得分:1)
首先,您必须按照此处所述定义您的连接:How to Work with multiple Entity Managers and Connections。
然后您可以创建一个服务,根据用户组返回适当的实体管理器。
服务定义:
app.user_database_helper:
class: AppBundle\UserDatabaseHelper
arguments:
- "@security.token_storage"
- "@doctrine"
服务类:
namespace AppBundle;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
class UserDatabaseHelper
{
private $tokenStorage;
private $doctrine;
public function __construct(TokenStorage $tokenStorage, Registry $doctrine)
{
$this->tokenStorage = $tokenStorage;
$this->doctrine = $doctrine;
}
public function getManager()
{
$token = $this->tokenStorage->getToken();
if (!$token) {
// return an entity manager for unauthenticated users
return $this->doctrine->getManager('unauthenticated');
}
$user = $token->getUser();
// set the manager name based on the user data
$managerName = ...;
return $this->doctrine->getManager($managerName);
}
}
在您的控制器中,您可以使用以下方式获取实体管理器:
$manager = $this->get('app.user_database_helper')->getManager();