Last active
June 3, 2016 12:47
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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