I have been developing multilanguage website based on Symfony4. Structure of one of the tables:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
id | int(11) | NO | PRI | NULL | auto_increment |
title_en | varchar(255) | NO | NULL | ||
title_fr | varchar(255) | NO | NULL | ||
title_de | varchar(255) | NO | NULL | ||
parent_id | int(11) | NO | NULL |
What is the optimal way to select appropriate column in template depending on user locale?
How bad will look the approach below to get needed entity field?
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* @ORM\Table(name="category")
* @ORM\Entity
*/
class Category
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title_en", type="string", length=255, nullable=false)
*/
private $titleEn;
/**
* @var string
*
* @ORM\Column(name="title_fr", type="string", length=255, nullable=false)
*/
private $titleFr;
/**
* @var string
*
* @ORM\Column(name="title_de", type="string", length=255, nullable=false)
*/
private $titleDe;
/**
* @var int
*
* @ORM\Column(name="parent_id", type="integer", nullable=false)
*/
private $parentId = '0';
public function getId(): ?int
{
return $this->id;
}
public function getLocalizedTitle(): ?string
{
$locale='title'.ucfirst($GLOBALS['request']->getLocale());
return $this->{$locale};
}
public function getTitleEn(): ?string
{
return $this->titleEn;
}
public function setTitleEn(string $titleEn): self
{
$this->titleEn = $titleEn;
return $this;
}
public function getTitleDe(): ?string
{
return $this->titleDe;
}
public function setTitleDe(string $titleDe): self
{
$this->titleDe = $titleDe;
return $this;
}
public function getParentId(): ?int
{
return $this->parentId;
}
public function setParentId(int $parentId): self
{
$this->parentId = $parentId;
return $this;
}
}
Then in view to get field we just use
{{ job.category.getLocalizedTitle }}