Spomky-Labs / pwa-bundle

PHP library for generating a full featured PWA manifest
https://pwa.spomky-labs.com
MIT License
28 stars 1 forks source link

How to implement a custom strategy #146

Closed tacman closed 3 weeks ago

tacman commented 2 months ago

Description

I really want to come up with a way to bulk add pages to the warmup_urls, e.g. a list of categories. I thought I could implement my own caching strategy, but I'm getting an error.

Class "SpomkyLabs\PwaBundle\Service\HasCacheStrategies" not found while loading "Survos\PwaExtraBundle\CachingStrategy\DymamicCachingStrategy".

I'm sure this has something to do with the compiler pass or cache warmer or something like that. Maybe a priority? A DependsOn? That is, I can't load my bundle until the PwaBundle classes have been loaded. I guess. This is deep into Symfony,

Example

<?php

declare(strict_types=1);

namespace Survos\PwaExtraBundle\CachingStrategy;

use SpomkyLabs\PwaBundle\CachingStrategy\CacheStrategy;
use SpomkyLabs\PwaBundle\CachingStrategy\WorkboxCacheStrategy;
use SpomkyLabs\PwaBundle\Dto\ServiceWorker;
use SpomkyLabs\PwaBundle\Dto\Workbox;
use SpomkyLabs\PwaBundle\Service\HasCacheStrategies;
use SpomkyLabs\PwaBundle\WorkboxPlugin\ExpirationPlugin;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\SerializerInterface;

final readonly class DymamicCachingStrategy implements HasCacheStrategies
{
    private int $jsonOptions;

    private Workbox $workbox;

    public function __construct(
        ServiceWorker $serviceWorker,
        private SerializerInterface $serializer,
        #[Autowire('%kernel.debug%')]
        bool $debug,
    ) {
        $this->workbox = $serviceWorker->workbox;

And in my bundle:

        $builder->autowire(DymamicCachingStrategy::class)
            ->setAutoconfigured(true)
            ->setPublic(true)
//            ->setArgument('$workbox', new Reference('workbox'))
            ->addTag('spomky_labs_pwa.cache_strategy')
        ;
Spomky commented 2 months ago

Hi,

I reorganized the classes and namespace. https://github.com/Spomky-Labs/pwa-bundle/blob/1.1.x/src/CachingStrategy/HasCacheStrategies.php

Note that I will turn the abstract class CacheStrategy into an interface and rename this class. This will allow custom strategy renderers

tacman commented 2 months ago

Thanks. Can you rename the interfaces to have an Interface suffix? That's pretty standard practice, and will make it clearer.

Ditto for ServiceWorkerRule -> ServiceWorkerRuleInterface

Can we leave this open until that's ready? I'm not even sure my approach is correct for precaching urls, but one way or another there's a way to do it. I've toyed with a script that generates yaml that can be included in the pwa.yaml file, which might be okay for a proof of concept but feels clunky.

Spomky commented 3 weeks ago

Closing as done.