barthy-koeln / cached-prezent-translation
Provides a trait to be used with prezent/translatable-bundle
Fund package maintenance!
barthy-koeln
Requires
- php: ^7.4|^8.1
- prezent/doctrine-translatable-bundle: ^1.2
Requires (Dev)
- barthy-koeln/beautify-specify: ^1.0
- brainmaestro/composer-git-hooks: ^2.8
- codeception/assert-throws: ^1.1
- friendsofphp/php-cs-fixer: ^2.16
- phpmd/phpmd: ^2.9
- phpunit/phpunit: ^9.4
- squizlabs/php_codesniffer: ^3.5
README
This library provides a simple trait that can be used with the prezent/doctrine-translatable-bundle
.
This is mostly a copy-pasted php trait from the prezent/doctrine-translatable
docs about proxy getters and setters, adapted for php >= 7.4 and opinionated code styles.
The trait stores the current locale, fallback locale, and caches the last fetched translation.
Usually, only one translation is necessary for an app: the current locale's translation or the fallback translation.
Since prezent/translatable-bundle
uses FETCH_EXTRA_LAZY
,
the cached translation does not trigger any additional straight SELECT statements if queried from the object multiple times.
In a situation where more than one translation is needed (i.e. multiple translations must be loaded for the application, it is best to either manually fully initialise the collection or to handle caching yourself.
Installation
composer require barthy-koeln/cached-prezent-translation
Usage
Entity
<?php use BarthyKoeln\CachedPrezentTranslation\CachedPrezentTranslationTrait; use Doctrine\Common\Collections\ArrayCollection; use Prezent\Doctrine\Translatable\Entity\AbstractTranslatable; class TranslatedEntity extends AbstractTranslatable { use CachedPrezentTranslationTrait; /** * @Assert\Valid() * @Prezent\Translations(targetEntity="App\Entity\TranslatedEntityTranslation") * @var ArrayCollection */ protected $translations; public function __construct() { $this->translations = new ArrayCollection(); } public function getTitle(?string $locale = null): string { return $this->translate($locale)->getTitle(); } }