Skip to content

Propose a way for user to use symfony cache with #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/LazyImage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,64 @@ php vendor/bin/phpunit
cd Resources/assets
yarn test
```

## Want to implement a cache ?

Use symfony/cache

```
composer require symfony/cache
```

And create your twig extension :

```php
<?php

namespace App\Twig;

use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\UX\LazyImage\BlurHash\BlurHashInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class BlurHashExtension extends AbstractExtension
{
public function __construct(private BlurHashInterface $blurHash, private CacheInterface $cache)
{}
Comment on lines +168 to +169
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is PHP 8 code and I don't think we want documentation/examples to be written with.
I think it would be better to write code compatible with the lowest PHP requirement which is 7.2.5.

WDYT?


public function getFunctions(): array
{
return [
new TwigFunction('data_uri_thumbnail_cached', [$this, 'createDataUriThumbnailCached']),
];
}

public function createDataUriThumbnailCached(string $filename, int $width, int $height, int $encodingWidth = 75, int $encodingHeight = 75): string
{
$slugger = new AsciiSlugger();
$cacheKey = $slugger->slug(implode('-', func_get_args()));

$value = $this->cache->get($cacheKey, function (ItemInterface $item) use ($filename, $width, $height, $encodingWidth, $encodingHeight) {
return $this->blurHash->createDataUriThumbnail($filename, $width, $height, $encodingWidth, $encodingHeight);
});

return $value;
}
}
```

And now in your images :

```twig
<img
src="{{ data_uri_thumbnail_cached('https://placeimg.com/970/550', 100, 75) }}"
data-controller="symfony--ux-lazy-image--lazy-image"
data-hd-src="https://placeimg.com/970/550?q={{ i }}"
width="970"
height="550"
alt="Image-Descrition">
```