Skip to content

Instantly share code, notes, and snippets.

@gnugat
Last active June 6, 2019 09:32
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gnugat/8314217 to your computer and use it in GitHub Desktop.
Save gnugat/8314217 to your computer and use it in GitHub Desktop.
Declaring a Doctrine Repository as a service and injecting it a dependency.
<?php
namespace Acme\DemoBundle\Repository;
use Acme\DemoBundle\Dependency;
use Doctrine\ORM\EntityRepository;
/**
* Get this repository directly from the container: it will set the $dependency attribute.
* If you get it using Doctrine's "getRepository()", don't forget to call setDependency().
*/
class ExampleRepository extends EntityRepository
{
/**
* @var Dependency
*/
private $dependency;
public function setDependency(Dependency $dependency)
{
$this->dependency = $dependency;
}
public function findSomething(Directory $directory)
{
$dependency = $this->getDependency();
// Your DQL.
}
private function getDependency()
{
if (!$this->dependency instanceof Dependency) {
$message = array(
'trigger' => 'The "dependency" attribute is NULL.',
'possibleReason' => 'Did you retrieved this repository using "$doctrine->getRepository()"?',
'remedy' => 'If so, retrieve it instead directly from the container',
);
throw \LogicException(implode(' ', $message));
}
return $this->dependency;
}
}
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme_demo.dependency" class="Acme\DemoBundle\Dependency">
</service>
<service id="acme_demo.example_repository"
class="Acme\DemoBundle\Repository\ExampleRepository"
factory-service="doctrine"
factory-method="getRepository">
<argument>AcmeDemoBundle:ExampleRepository</argument>
<call method="setDependency">
<argument type="service" id="acme_demo.dependency" />
</call>
</service>
<service id="acme_demo.service" class="Acme\DemoBundle\Service">
<argument type="service" id="acme_demo.example_repository" />
</service>
</services>
</container>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment