Przyjęłam nieco inne rozwiązanie, korzystając z usług macierzystych Symfony2.
Przede wszystkim stworzyłem usługę rodzica, klasę GenericRepository
, która udostępnia kilka metod i ułatwia życie w przypadku, gdybyśmy chcieli w przyszłości zmienić kod.
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();
}
Teraz chcemy definiować nowe repozytorium:
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';
}
}
Sposób deleteBatch()
tworzy i wykonuje następujące zapytanie:
DELETE FROM product_batch WHERE id = ?
Wreszcie w naszym Kontroler:
public function deleteAction() {
$batchId = $this->getRequest()->get('batchId');
$affectedRows = $this->get('acme_product.repository.product_batch')->deleteBatch($batchId);
return $this->render(/**/);
}
W celu uzyskania dalszych informacji i kierownika jednostki/połączenie użycie proszę odnieść się do oficjalnej dokumentacji: http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html
Przepraszam, miałem na myśli, że repozytorium nie powinno być powiązane z żadnym podmiotem. Dlaczego więc chodzi o metadane? – gremo
@Gremo w takim przypadku byłoby sensowne utworzenie dodatkowej usługi i wstrzyknięcie samego połączenia z bazą danych. – gilden
po wstrzyknięciu database_connection powinienem utworzyć tylko klasę dziedziczącą z EntityRepository, czy mam rację? – gremo