rcrowe / TwigBridge

Give the power of Twig to Laravel
MIT License
894 stars 168 forks source link

How to use twigphp/cache-extra? #415

Open event15 opened 2 years ago

event15 commented 2 years ago

Hey, I am trying to use the twigphp/cache-extra (https://twig.symfony.com/doc/3.x/tags/cache.html) extension in TwigBridge.

In app/config/twigbridge.php I added in extensions->enabled section an entry:

TwigExtraCacheExtension::class,

When I try to use the cache block, I get an error:

ErrorException (E_ERROR)
Unable to load the "Twig\Extra\Cache\CacheRuntime" runtime.

The twig documentation says:

If you are not using Symfony, you must also register the extension runtime:

use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
use Twig\Extra\Cache\CacheRuntime;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

$twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
    public function load($class) {
        if (CacheRuntime::class === $class) {
            return new CacheRuntime(new TagAwareAdapter(new FilesystemAdapter()));
        }
    }
});

However, I have no idea where in the application to add such a loader. From what I see, extensions are added in this file: vendor/barryvdh/laravel-form-bridge/src/ServiceProvider.php

Does this mean I should overwrite this service provider and use a custom one?

adrienne commented 2 years ago

@rcrowe any help available here?

webard commented 1 year ago

Just add it to AppServiceProvider for example:

use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
use Twig\Extra\Cache\CacheRuntime;
use Twig\RuntimeLoader\RuntimeLoaderInterface;
...
class AppServiceProvider extends ServiceProvider
{
    public function boot() {
            $twig = app(\Twig\Environment::class);
            $twig->addRuntimeLoader(new class implements RuntimeLoaderInterface
            {
                public function load($class)
                {
                    if (CacheRuntime::class === $class) {
                        return new CacheRuntime(new TagAwareAdapter(new FilesystemAdapter()));
                    }
                }
            });
    }
}