Skip to content

Commit 1f0cde0

Browse files
cedriclombardotCedric LOMBARDOT
authored andcommitted
Propose a way for user to use symfony cache with
To not regenerate each time blurhash
1 parent 06521ce commit 1f0cde0

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/LazyImage/README.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,70 @@ php vendor/bin/phpunit
139139
cd Resources/assets
140140
yarn test
141141
```
142+
143+
## Want to implement a cache ?
144+
145+
Use symfony/cache
146+
147+
```
148+
composer require symfony/cache
149+
```
150+
151+
And create your twig extension :
152+
153+
```php
154+
<?php
155+
156+
namespace App\Twig;
157+
158+
use Symfony\Component\String\Slugger\AsciiSlugger;
159+
use Symfony\Contracts\Cache\CacheInterface;
160+
use Symfony\Contracts\Cache\ItemInterface;
161+
use Symfony\UX\LazyImage\BlurHash\BlurHashInterface;
162+
use Twig\Extension\AbstractExtension;
163+
use Twig\TwigFilter;
164+
use Twig\TwigFunction;
165+
166+
class BlurHashExtension extends AbstractExtension
167+
{
168+
public function __construct(private BlurHashInterface $blurHash, private CacheInterface $cache)
169+
{}
170+
171+
public function getFunctions(): array
172+
{
173+
return [
174+
new TwigFunction('data_uri_thumbnail_cached', [$this, 'createDataUriThumbnailCached']),
175+
];
176+
}
177+
178+
public function createDataUriThumbnailCached(string $filename, int $width, int $height, int $encodingWidth = 75, int $encodingHeight = 75): string
179+
{
180+
$slugger = new AsciiSlugger();
181+
$cacheKey = $slugger->slug(implode('-', func_get_args()));
182+
183+
$value = $this->cache->get($cacheKey, function (ItemInterface $item) use ($filename, $width, $height, $encodingWidth, $encodingHeight) {
184+
if (!$item->isHit()) {
185+
$item->set(
186+
$this->blurHash->createDataUriThumbnail($filename, $width, $height, $encodingWidth, $encodingHeight)
187+
);
188+
}
189+
190+
return $item->get();
191+
});
192+
193+
return $value;
194+
}
195+
}
196+
```
197+
198+
And now in your images :
199+
200+
```twig
201+
<img
202+
src="{{ data_uri_thumbnail_cached('https://placeimg.com/970/550', 100, 75) }}"
203+
data-controller="symfony--ux-lazy-image--lazy-image"
204+
data-hd-src="https://placeimg.com/970/550?q={{ i }}"
205+
width="970"
206+
height="550"
207+
alt="Image-Descrition">
208+
```

0 commit comments

Comments
 (0)