Having a custom repository not associated to an en

2019-01-23 15:43发布

问题:

Would be possible to have a custom repository not associated with an entity in Symfony 2 and Doctrine 2? I would like to put in it some native SQL that doesn't fit well in other repositories (it may refer to abstract or entity hierarchy).

How controller code $this->getDoctrine()->getRepositoty(/* ??? */) should be replaced?

回答1:

It's possible to have as many repositories as you wish. However, only a single repository can be linked with the entity manager.

You need to define a few services to add a custom repository.

<!-- 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>

The repository class would have to inherit from 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);
     * }
     *
     */
}

Unfortunately you'll not be able to retrieve it via the doctrine service. Instead, retrieve it straight from the container:

$this->get('acme.repository.my_entity');

EDIT

If you're creating a repository that shouldn't be linked to any entities, simply create a service and inject the necessary dependencies.

<!-- Repository for misc queries -->
<service id="acme.repository.misc" class="Acme\FQCN\MiscRepsitory">
    <argument type="service" id="database_connection" />
</service>

Since you're not using any of the Doctrine's ORM features in a custom repository, there's no need to extend EntityManager.

namespace Acme\FQCN;

use \Doctrine\DBAL\Connection;

class MiscRepository
{
    protected $conn;

    public function __construct(Connection $conn)
    {
        $this->conn = $conn;
    }
}


回答2:

I adopted a slightly different solution using Symfony2 parent services.

First of all I created a parent service, a GenericRepository class that exposes a couple of methods and makes life easier in case we'd like to refactor our code in the future.

services.yml

acme_core.generic_repository:
    abstract: true
    class: Acme\Bundle\CoreBundle\Repository\GenericRepository
    arguments: [@doctrine.orm.entity_manager]

Acme\Bundle\CoreBundle\Repository\GenericRepository

<?php

namespace Acme\Bundle\CoreBundle\Repository;

use Doctrine\ORM\EntityManager;

/**
 * Class GenericRepository
 * @package Acme\Bundle\CoreBundle\Repository
 */
abstract class GenericRepository {
    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager) {
        $this->entityManager = $entityManager;
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager() {
        return $this->entityManager;
    }

    /**
     * @return \Doctrine\DBAL\Connection
     */
    public function getConnection() {
        return $this->getEntityManager()->getConnection();
    }

    /**
     * @return string
     */
    abstract function getTable();
}

Now we want to define a new repository:

services.yml

# Repositories
acme_product.repository.product_batch:
    parent: acme_core.generic_repository
    class: Acme\Bundle\ProductBundle\Repository\ProductBatchRepository

Acme\Bundle\ProductBundle\Repository\ProductBatchRepository

<?php

namespace Acme\Bundle\ProductBundle\Repository;

use Acme\Bundle\CoreBundle\Repository\GenericRepository;

/**
 * Class ProductBatchRepository
 * @package Acme\Bundle\ProductBundle\Repository
 */
class ProductBatchRepository extends GenericRepository {
    /**
     * @param int $batchId
     * @return integer The number of affected rows.
     */
    public function deleteBatch($batchId) {
        $table = $this->getTable();

        return $this->getConnection()->delete($table, [
            'id' => $batchId
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getTable() {
        return 'product_batch';
    }
}

The deleteBatch() method creates and executes the following query:

DELETE FROM product_batch WHERE id = ?

Finally in our controller:

public function deleteAction() {
    $batchId = $this->getRequest()->get('batchId');

    $affectedRows = $this->get('acme_product.repository.product_batch')->deleteBatch($batchId);

    return $this->render(/**/);
}

For further information and entity manager / connection usage please refer to the official documentation: http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html



回答3:

My suggestion is to create a plain PHP class with the needed dependencies in the constructor and get it through the service container.