Skip to content

Instantly share code, notes, and snippets.

@weaverryan weaverryan/CoolStuff.php
Last active Nov 6, 2017

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Nov 6, 2017

Why not singleton?

@TomasVotruba

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Nov 6, 2017

awesome! 👍

@weaverryan

This comment has been minimized.

Copy link
Owner Author

commented Nov 6, 2017

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
You can’t perform that action at this time.