是否有可能在 Symfony 2 和 Doctrine 2 中拥有一个不与实体关联的自定义存储库?我想在其中放入一些不适合其他存储库的 native SQL(它可能引用抽象或实体层次结构)。
如何 Controller 代码$this->getDoctrine()->getRepositoty(/* ??? */)
应该更换?
最佳答案
您可以拥有任意数量的存储库。但是,只有一个存储库可以与实体管理器链接。
您需要定义一些服务来添加自定义存储库。
<!-- My custom repository -->
<service id="acme.repository.my_entity" class="Acme\FQCN\MyEntityRepository" >
<argument type="service" id="doctrine.orm.entity_manager" />
<argument type="service" id="acme.metadata.my_entity" />
</service>
<!-- MyEntity metadata -->
<service id="acme.metadata.my_entity" class="Doctrine\ORM\Mapping\ClassMetaData">
<argument>Acme\FQCN\MyEntity</argument>
</service>
存储库类必须继承自
EntityRepository
.namespace Acme\FQCN;
use Doctrine\ORM\EntityRepository;
class MyEntityRepository extends EntityRepository
{
/**
* If you want to inject any custom dependencies, you'd have either have to
* add them to the construct or create setters. I'd suggest using setters
* in which case you wouldn't need to use the constructor in this class.
*
* public function __construct($em, Doctrine\ORM\Mapping\ClassMetadata $class, $custom_dependency)
* {
* parent::__construct($em, $class);
* }
*
*/
}
不幸的是,您将无法通过 Doctrine 服务检索它。相反,直接从容器中检索它:
$this->get('acme.repository.my_entity');
编辑
如果您正在创建不应链接到任何实体的存储库,只需创建一个服务并注入(inject)必要的依赖项。
<!-- Repository for misc queries -->
<service id="acme.repository.misc" class="Acme\FQCN\MiscRepsitory">
<argument type="service" id="database_connection" />
</service>
由于您没有在自定义存储库中使用任何 Doctrine 的 ORM 功能,因此无需扩展
EntityManager
.namespace Acme\FQCN;
use \Doctrine\DBAL\Connection;
class MiscRepository
{
protected $conn;
public function __construct(Connection $conn)
{
$this->conn = $conn;
}
}
关于symfony - 在 Symfony 2/Doctrine 2 中有一个与实体没有关联的自定义存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11411183/