Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Last active November 6, 2017 22:01
Show Gist options
  • 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}'
@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