Класс ServiceEntityRepository
Класс ServiceEntityRepository наследуется от EntityRepository
и используется для создания репозиториев сущностей в Symfony.
Первым параметром в конструктор передаётся ManagerRegistry,
а вторым - класс сущности, для которой создаётся репозиторий.
Класс автоматически регистрируется как сервис и может внедряться
в контроллеры и другие сервисы через механизм автовайринга.
Синтаксис
<?php
use DoctrineBundleDoctrineBundleRepositoryServiceEntityRepository;
use DoctrinePersistenceManagerRegistry;
class ArticleRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Article::class);
}
}
?>
Пример
Давайте создадим сущность Article с полями title и text:
<?php
namespace AppEntity;
use DoctrineORMMapping as ORM;
use AppRepositoryArticleRepository;
#[ORMEntity(repositoryClass: ArticleRepository::class)]
class Article
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn(type: 'integer')]
private int $id;
#[ORMColumn(type: 'string', length: 255)]
private string $title;
#[ORMColumn(type: 'text')]
private string $text;
public function getId(): int
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getText(): string
{
return $this->text;
}
public function setText(string $text): self
{
$this->text = $text;
return $this;
}
}
?>
Теперь создадим репозиторий ArticleRepository на основе класса ServiceEntityRepository:
<?php
namespace AppRepository;
use AppEntityArticle;
use DoctrineBundleDoctrineBundleRepositoryServiceEntityRepository;
use DoctrinePersistenceManagerRegistry;
class ArticleRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Article::class);
}
}
?>
Пример
Давайте внедрим репозиторий в контроллер и найдём все статьи:
<?php
namespace AppController;
use AppRepositoryArticleRepository;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/', name: 'article_index')]
public function index(ArticleRepository $repository): Response
{
$res = $repository->findAll();
return new Response(count($res));
}
}
?>
Результат выполнения кода при трёх статьях в базе:
"3"
Пример
Давайте добавим в репозиторий собственный метод для поиска статьи по заголовку:
<?php
namespace AppRepository;
use AppEntityArticle;
use DoctrineBundleDoctrineBundleRepositoryServiceEntityRepository;
use DoctrinePersistenceManagerRegistry;
class ArticleRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Article::class);
}
public function findByTitle(string $title): ?Article
{
return $this->createQueryBuilder('a')
->andWhere('a.title = :title')
->setParameter('title', $title)
->getQuery()
->getOneOrNullResult();
}
}
?>
Теперь используем этот метод в контроллере:
<?php
namespace AppController;
use AppRepositoryArticleRepository;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article/{title}', name: 'article_show')]
public function show(string $title, ArticleRepository $repository): Response
{
$article = $repository->findByTitle($title);
if (!$article) {
return new Response('not found');
}
return new Response($article->getText());
}
}
?>
Результат выполнения кода для адреса /article/hello:
"article text"
Смотрите также
-
метод
find,
который находит сущность по идентификатору -
метод
findAll,
который возвращает все сущности репозитория -
метод
findBy,
который находит сущности по заданным критериям -
метод
createQueryBuilder,
который создаёт конструктор запросов Doctrine