/**
* @ORM\Column(name="name", length=64)
*/
private $name_ru;
/**
* @ORM\Column(length=64, nullable=true)
*/
private $name_cn;
/**
* @ORM\Column(length=64, nullable=true)
*/
private $name_en;
/**
* @param $name
* @param string $lang
*/
public function setName($name, $lang = "ru")
{
$this->{"name_$lang"} = $name;
}
/**
* @param string $lang
* @return mixed
*/
public function getName($lang = "ru")
{
return $this->{"name_$lang"};
}
<?php
namespace App\Classes\Entity;
/**
* Class AbstractEntity
* @package App\Classes\Entity
*/
abstract class AbstractEntity
{
/** @var string */
protected $language = "ru";
/**
* @param string $language
*/
public function setLanguage(string $language): void
{
$this->language = $language;
}
}
<?php
namespace App\Entity;
use App\Classes\Entity\AbstractEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
* @ORM\Table(name="categories")
*/
class Category extends AbstractEntity
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue
*/
private $id;
/**
* @ORM\Column(name="name", length=64)
*/
private $name_ru;
/**
* @ORM\Column(length=64, nullable=true)
*/
private $name_cn;
/**
* @ORM\Column(length=64, nullable=true)
*/
private $name_en;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param $name
* @param string $lang
*/
public function setName($name, $lang)
{
$this->{"name_$lang"} = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->{"name_$this->language"};
}
}
<?php
namespace App\Listeners;
use App\Classes\Entity\AbstractEntity;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class LanguageEntityListener
* @package App\Listeners
*/
class LanguageEntityListener
{
/** @var string */
private $language = "ru";
/** @var Request */
private $request;
/**
* LanguageEntityListener constructor.
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();
$this->language = $this->request->get("lang", "ru");
}
public function postLoad(LifecycleEventArgs $event)
{
$entity = $event->getObject();
if (is_a($entity, AbstractEntity::class)) {
$entity->setLanguage($this->language);
}
}
}
services:
app.listeners.language_entity_listener:
class: App\Listeners\LanguageEntityListener
arguments: ['@request_stack']
tags:
- { name: doctrine.event_listener, event: postLoad, method: postLoad }