我们在一些项目上做同样的事情。
我们已经完成了以下步骤:
我们编写的存储库只是定义为服务的类,并将接收作为构造函数注入的学说连接。然后,您可以获得连接并使用 PDO。
存储库类的示例(请注意,我们只是将它们称为存储库,因为它们处理数据库查询,但它们与 Symfony / Doctrine 中的存储库类无关)
class DemoRepositoryClass
{
private $connection;
public function __construct(Registry $doctrine)
{
// Get the database connection from doctrine
$this->connection = $doctrine->getConnection();
}
public function test()
{
$query = "SELECT * FROM XXX WHERE FOO = 'BAZ";
$stmt = $this->conncetion->prepare($query);
// [...] Do as always with PDO;
}
}
此类将在 services.yml 中定义为服务
app.demo_repository_class:
class: AppBundle\Path\DemoRepositoryClass
arguments: ['@doctrine']
public: true
这样,您可以从控制器调用服务功能,例如:
// In a controller action/function
$this->get('app.demo_repository_class')->test();