barthy-koeln/cached-prezent-translation

Provides a trait to be used with prezent/translatable-bundle

1.0.0 2020-11-10 17:28 UTC

This package is auto-updated.

Last update: 2021-09-10 19:11:35 UTC


README

CircleCI Coverage

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();
    }
}