Я следовал инструкциям на https://symfony.com/doc/current/doctrine/events.html#doctrine-lifecycle-listeners, и я не знаю, что я делаю неправильно. Но события не срабатывают.
Слушатель событий возьмет слаг и, если слаг будет таким же, как я, я добавлю Id из статьи к слагу.
namespace App\EventListener;
use App\Entity\Article;
use App\Repository\ArticleRepository;
use App\Service\SlugifyService;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
class SlugIndexer implements EventSubscriber
{
private $repository;
private $slugify;
public function __construct(ArticleRepository $repository, SlugifyService $slugifyService)
{
$this->repository = $repository;
$this->slugify = $slugifyService;
}
public function getSubscribedEvents()
{
return [
Events::postPersist,
Events::preUpdate,
];
}
public function preUpdate(Article $article, PreUpdateEventArgs $event)
{
$articleSlug = $this->slugify->slugify($article->getTitle());
if ($this->repository->findOneBy(['slug' => $articleSlug])) {
$articleSlug .= '-' . $article->getId();
}
$article->setSlug($articleSlug);
}
public function postPersist(LifecycleEventArgs $args)
{
$article = $args->getObject();
if (!($article instanceof Article)) {
return;
}
$articleSlug = $this->slugify->slugify($article->getTitle());
if ($this->repository->findOneBy(['slug' => $articleSlug])) {
$articleSlug .= '-' . $article->getId();
}
$article->setSlug($articleSlug);
$args->getObjectManager()->persist($article);
$args->getObjectManager()->flush();
}
}
Это код из моей сущности Article.
<?php
namespace App\Entity;
use App\Entity\User\User;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
* @ORM\Table(name="articles")
*/
class Article implements EntityInterface
{
/**
* @var int
*
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*
*/
private $title;
/**
* @ORM\Column(type="string", length=255)
*/
private $lead;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*
*/
private $slug;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $content;
/**
* @ORM\Column(type="datetime")
*/
private $publishedAt;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="articles")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)
*
*/
private $category;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User\User", inversedBy="articles")
* @ORM\JoinColumn(nullable=false)
*/
private $author;
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 getLead(): ?string
{
return $this->lead;
}
public function setLead(string $lead): self
{
$this->lead = $lead;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getPublishedAt(): ?\DateTimeInterface
{
return $this->publishedAt;
}
public function setPublishedAt(\DateTimeInterface $publishedAt): self
{
$this->publishedAt = $publishedAt;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
}
ArticleController Это код, как я создаю новую статью.
/**
* @Route(path="/article", methods={"POST", "GET"})
*/
public function create(Request $request, SlugifyService $slugifyService): Response
{
$article = new Article();
$form = $this->createForm(ArticleFormType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$article->setPublishedAt(new \DateTime('now'));
$this->repository->save($article);
return $this->redirectToRoute('app_category_view', [
'slug' => $article->getCategory()->getSlug()
]);
}
return $this->render('layouts/article/createArticle.html.twig', [
'articleForm' => $form->createView()
]);
}