Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Last active November 6, 2017 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaverryan/eec33e4a6d3f98efd3b56939bc08697d to your computer and use it in GitHub Desktop.
Save weaverryan/eec33e4a6d3f98efd3b56939bc08697d to your computer and use it in GitHub Desktop.
Autowireable & Auto-registered Repository Services in Doctrine 1.8
<?php
// Coming in DoctrineBundle 1.8: https://github.com/doctrine/DoctrineBundle/pull/727
/* *********************
src/Entity/CoolStuff.php
/* ********************* */
/**
* @ORM\Entity(repositoryClass="App\Repository\CoolStuffRepository")
*/
class CoolStuff
{
}
/* *********************
src/Repository/CoolStuffRepository.php
/* ********************* */
class CoolStuffRepository extends ServiceEntityRepository
{
// your custom methods
}
/* *********************
src/Controller/AnyController.php
/* ********************* */
class AnyController
{
public function anyAction(CoolStuffRepository $repo)
{
// $repo->myCustomMethod();
}
}
/* *********************
src/Service/AnyService.php
/* ********************* */
class AnyService
{
private $repo;
public function __construct(CoolStuffRepository $repo)
{
$this->repo = $repo;
}
}
# config/services.yaml
services:
# ...
App\:
resource: '../src/*'
# just remove Repository from exclude :)
- exclude: '../src/{Entity,Migrations,Repository,Tests}'
+ exclude: '../src/{Entity,Migrations,Tests}'
@antonmedv
Copy link

Why not singleton?

@TomasVotruba
Copy link

TomasVotruba commented Nov 6, 2017

Why not SOLID, without magic, Doctrine-agnostic (easy to replace) and framework-independent?

https://www.tomasvotruba.cz/blog/2017/10/16/how-to-use-repository-with-doctrine-as-service-in-symfony/

Just be aware of huge confusion about Symfony Doctrine and Repository on Stackoverflow already. This might brign many new questions, unnecessary questions.

How can I have 2 repositories for 1 entity? Etc.

@tystr
Copy link

tystr commented Nov 6, 2017

awesome! 👍

@weaverryan
Copy link
Author

Actually, we read your post when designing this @TomasVotruba and a lot of thought went into the options. You can check out the serveal related PR’s for the multiple different approaches.

Ultimately, since there is - and always will be (for better or worse) a repository system in Doctrine, it made more sense to use that one system, instead of creating 2 separate ideas of a repository (the one in Doctrine and your new, pure service). This also makes migrating to the new system almost effortless and plays better with things like the EntityType.

The cool thing is that if users want to ignore their repositories and create pure services, that’s great and already possible. I know some users will do this, and that’s awesome - we have that flexibility :).

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment