Skip to content

Instantly share code, notes, and snippets.

@jeroenvdgulik
Last active June 3, 2016 12:47
Show Gist options
  • Save jeroenvdgulik/4b7684e9dfb93eda12591faeee4ffa4a to your computer and use it in GitHub Desktop.
Save jeroenvdgulik/4b7684e9dfb93eda12591faeee4ffa4a to your computer and use it in GitHub Desktop.
How to create a Repository as a Service with optional dependancies in Symfony3
<?php
namespace Foo\SomeBundle\Repository;
use Foo\SomeBundle\Dependency;
use Doctrine\ORM\EntityRepository;
class SomeRepository extends EntityRepository implements SomeContract
{
/**
* @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) {
throw \LogicException('Missing Dependency');
}
return $this->dependency;
}
}
services:
foo.dependency:
class: Foo\SomeBundle\Dependency
foo.some_repository:
class: Foo\SomeBundle\Repository\SomeRepository
factory: ['@doctrine.orm.entity_manager', getRepository]
arguments: ['Foo\SomeBundle\Entity\TheEntity']
calls:
- [setDependency, ['@foo.dependency']]
actual.service.that.needs.repository:
class: Foo\BarBundle\Service
arguments: ['@foo.some_repository']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment