Skip to content

Commit c44e958

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 c44e958

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/LazyImage/README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,65 @@ 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+
return $this->blurHash->createDataUriThumbnail($filename, $width, $height, $encodingWidth, $encodingHeight)
185+
);
186+
});
187+
188+
return $value;
189+
}
190+
}
191+
```
192+
193+
And now in your images :
194+
195+
```twig
196+
<img
197+
src="{{ data_uri_thumbnail_cached('https://placeimg.com/970/550', 100, 75) }}"
198+
data-controller="symfony--ux-lazy-image--lazy-image"
199+
data-hd-src="https://placeimg.com/970/550?q={{ i }}"
200+
width="970"
201+
height="550"
202+
alt="Image-Descrition">
203+
```

0 commit comments

Comments
 (0)