Skip to content

Make Doctrine repository as service and autowire/use it anywhere #701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 24, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"require": {
"php": "^7.1.3",
"ext-pdo_sqlite": "*",
"doctrine/doctrine-bundle": "^1.8",
"doctrine/doctrine-fixtures-bundle": "^2.4",
"erusev/parsedown": "^1.6",
"ezyang/htmlpurifier": "^4.9",
Expand Down
2 changes: 1 addition & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ services:
resource: '../src/*'
# you can exclude directories or files
# but if a service is unused, it's removed anyway
exclude: '../src/{DataFixtures,Entity,Migrations,Repository,Tests}'
exclude: '../src/{DataFixtures,Entity,Migrations,Tests}'

# controllers are imported separately to make sure they're public
# and have a tag that allows actions to type-hint services
Expand Down
11 changes: 6 additions & 5 deletions src/Command/AddUserCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace App\Command;

use App\Entity\User;
use App\Repository\UserRepository;
use App\Utils\Validator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
Expand Down Expand Up @@ -57,14 +58,16 @@ class AddUserCommand extends Command
private $entityManager;
private $passwordEncoder;
private $validator;
private $users;

public function __construct(EntityManagerInterface $em, UserPasswordEncoderInterface $encoder, Validator $validator)
public function __construct(EntityManagerInterface $em, UserPasswordEncoderInterface $encoder, Validator $validator, UserRepository $users)
{
parent::__construct();

$this->entityManager = $em;
$this->passwordEncoder = $encoder;
$this->validator = $validator;
$this->users = $users;
}

/**
Expand Down Expand Up @@ -202,10 +205,8 @@ protected function execute(InputInterface $input, OutputInterface $output)

private function validateUserData($username, $plainPassword, $email, $fullName)
{
$userRepository = $this->entityManager->getRepository(User::class);

// first check if a user with the same username already exists.
$existingUser = $userRepository->findOneBy(['username' => $username]);
$existingUser = $this->users->findOneBy(['username' => $username]);

if (null !== $existingUser) {
throw new RuntimeException(sprintf('There is already a user registered with the "%s" username.', $username));
Expand All @@ -217,7 +218,7 @@ private function validateUserData($username, $plainPassword, $email, $fullName)
$this->validator->validateFullName($fullName);

// check if a user with the same email already exists.
$existingEmail = $userRepository->findOneBy(['email' => $email]);
$existingEmail = $this->users->findOneBy(['email' => $email]);

if (null !== $existingEmail) {
throw new RuntimeException(sprintf('There is already a user registered with the "%s" email.', $email));
Expand Down
9 changes: 6 additions & 3 deletions src/Command/DeleteUserCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace App\Command;

use App\Entity\User;
use App\Repository\UserRepository;
use App\Utils\Validator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
Expand Down Expand Up @@ -42,16 +43,19 @@ class DeleteUserCommand extends Command
{
protected static $defaultName = 'app:delete-user';

/** @var SymfonyStyle */
private $io;
private $entityManager;
private $validator;
private $users;

public function __construct(EntityManagerInterface $em, Validator $validator)
public function __construct(EntityManagerInterface $em, Validator $validator, UserRepository $users)
{
parent::__construct();

$this->entityManager = $em;
$this->validator = $validator;
$this->users = $users;
}

/**
Expand Down Expand Up @@ -108,9 +112,8 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$username = $this->validator->validateUsername($input->getArgument('username'));

$repository = $this->entityManager->getRepository(User::class);
/** @var User $user */
$user = $repository->findOneByUsername($username);
$user = $this->users->findOneByUsername($username);

if (null === $user) {
throw new RuntimeException(sprintf('User with username "%s" not found.', $username));
Expand Down
12 changes: 6 additions & 6 deletions src/Command/ListUsersCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace App\Command;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\UserRepository;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
Expand All @@ -39,17 +39,17 @@ class ListUsersCommand extends Command
// a good practice is to use the 'app:' prefix to group all your custom application commands
protected static $defaultName = 'app:list-users';

private $entityManager;
private $mailer;
private $emailSender;
private $users;

public function __construct(EntityManagerInterface $em, \Swift_Mailer $mailer, $emailSender)
public function __construct(\Swift_Mailer $mailer, $emailSender, UserRepository $users)
{
parent::__construct();

$this->entityManager = $em;
$this->mailer = $mailer;
$this->emailSender = $emailSender;
$this->users = $users;
}

/**
Expand Down Expand Up @@ -91,7 +91,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$maxResults = $input->getOption('max-results');
// Use ->findBy() instead of ->findAll() to allow result sorting and limiting
$users = $this->entityManager->getRepository(User::class)->findBy([], ['id' => 'DESC'], $maxResults);
$allUsers = $this->users->findBy([], ['id' => 'DESC'], $maxResults);

// Doctrine query returns an array of objects and we need an array of plain arrays
$usersAsPlainArrays = array_map(function (User $user) {
Expand All @@ -102,7 +102,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$user->getEmail(),
implode(', ', $user->getRoles()),
];
}, $users);
}, $allUsers);

// In your console commands you should always use the regular output type,
// which outputs contents directly in the console window. However, this
Expand Down
8 changes: 4 additions & 4 deletions src/Controller/Admin/BlogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use App\Entity\Post;
use App\Form\PostType;
use App\Repository\PostRepository;
use App\Utils\Slugger;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
Expand Down Expand Up @@ -54,12 +55,11 @@ class BlogController extends AbstractController
* @Route("/", name="admin_post_index")
* @Method("GET")
*/
public function index(): Response
public function index(PostRepository $posts): Response
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository(Post::class)->findBy(['author' => $this->getUser()], ['publishedAt' => 'DESC']);
$authorPosts = $posts->findBy(['author' => $this->getUser()], ['publishedAt' => 'DESC']);

return $this->render('admin/blog/index.html.twig', ['posts' => $posts]);
return $this->render('admin/blog/index.html.twig', ['posts' => $authorPosts]);
}

/**
Expand Down
14 changes: 7 additions & 7 deletions src/Controller/BlogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use App\Entity\Post;
use App\Events;
use App\Form\CommentType;
use App\Repository\PostRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
Expand Down Expand Up @@ -47,15 +48,14 @@ class BlogController extends AbstractController
* Content-Type header for the response.
* See https://symfony.com/doc/current/quick_tour/the_controller.html#using-formats
*/
public function index(int $page, string $_format): Response
public function index(int $page, string $_format, PostRepository $posts): Response
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository(Post::class)->findLatest($page);
$latestPosts = $posts->findLatest($page);

// Every template name also has two extensions that specify the format and
// engine for that template.
// See https://symfony.com/doc/current/templating.html#template-suffix
return $this->render('blog/index.'.$_format.'.twig', ['posts' => $posts]);
return $this->render('blog/index.'.$_format.'.twig', ['posts' => $latestPosts]);
Copy link
Member Author

@yceruto yceruto Nov 20, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about just ... ['posts' => $posts->findLatest($page)]?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure ... the line would be a bit long.

}

/**
Expand Down Expand Up @@ -148,18 +148,18 @@ public function commentForm(Post $post): Response
* @Route("/search", name="blog_search")
* @Method("GET")
*/
public function search(Request $request): Response
public function search(Request $request, PostRepository $posts): Response
{
if (!$request->isXmlHttpRequest()) {
return $this->render('blog/search.html.twig');
}

$query = $request->query->get('q', '');
$limit = $request->query->get('l', 10);
$posts = $this->getDoctrine()->getRepository(Post::class)->findBySearchQuery($query, $limit);
$foundPosts = $posts->findBySearchQuery($query, $limit);

$results = [];
foreach ($posts as $post) {
foreach ($foundPosts as $post) {
$results[] = [
'title' => htmlspecialchars($post->getTitle()),
'date' => $post->getPublishedAt()->format('M d, Y'),
Expand Down
10 changes: 8 additions & 2 deletions src/Repository/PostRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
namespace App\Repository;

use App\Entity\Post;
use Doctrine\ORM\EntityRepository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\Query;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
Expand All @@ -27,8 +28,13 @@
* @author Javier Eguiluz <[email protected]>
* @author Yonel Ceruto <[email protected]>
*/
class PostRepository extends EntityRepository
class PostRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Post::class);
}

public function findLatest(int $page = 1): Pagerfanta
{
$query = $this->getEntityManager()
Expand Down
10 changes: 8 additions & 2 deletions src/Repository/UserRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

namespace App\Repository;

use Doctrine\ORM\EntityRepository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;

/**
* This custom Doctrine repository is empty because so far we don't need any custom
Expand All @@ -23,6 +25,10 @@
* @author Ryan Weaver <[email protected]>
* @author Javier Eguiluz <[email protected]>
*/
class UserRepository extends EntityRepository
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
}
5 changes: 4 additions & 1 deletion tests/Command/AddUserCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use App\Command\AddUserCommand;
use App\Entity\User;
use App\Utils\Validator;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
Expand Down Expand Up @@ -117,7 +118,9 @@ private function executeCommand(array $arguments, array $inputs = [])
self::bootKernel();

$container = self::$kernel->getContainer();
$command = new AddUserCommand($container->get('doctrine')->getManager(), $container->get('security.password_encoder'), new Validator());
/** @var Registry $doctrine */
$doctrine = $container->get('doctrine');
$command = new AddUserCommand($doctrine->getManager(), $container->get('security.password_encoder'), new Validator(), $doctrine->getRepository(User::class));
$command->setApplication(new Application(self::$kernel));

$commandTester = new CommandTester($command);
Expand Down