Sonata Block and caching

123 views
Skip to first unread message

Willem van Duijn

unread,
Dec 3, 2014, 7:46:51 AM12/3/14
to sonata...@googlegroups.com
Hi,

I'm not using the Page (CMS) bundle, but I want to use the Block bundle, and I want Block's to be cached.

In my template, I've got a block for the header (amongst others):

{{ 
    sonata_block_render({ 'type': 'myproject_website.block.header' }, {
        'site_id': 1
    }) 
}}

This works well: the header is displayed correctly.

Now I want to cache the result, as the block involves many database queries. Everything is configured correctly, but every cache is a miss. The reason: the calculated cache key is different each time. I tracked down that the problem has to do with the ID of the Block (Block::$id).

The template gets parsed, and for each block Sonata\BlockBundle\Block\Loader\ServiceLoader::load is executed to create the Block object. This function uses uniqid() for the Block::$id, hence it is different on each request so for the same template block, each requests ends up with a different Block::$id hance a different cache key.

What am I doing wrong here? 

Thank you,

Willem van Duijn

khalid 05

unread,
Dec 3, 2014, 8:38:48 AM12/3/14
to sonata...@googlegroups.com
Hi,
page configuration:

cache_invalidation:
     service: sonata.page.cache.invalidation.simple
     recorder: sonata.page.cache.recorder
     classes:
          "Application\Sonata\PageBundle\Entity\Block": getId

Willem van Duijn

unread,
Dec 3, 2014, 9:01:49 AM12/3/14
to sonata...@googlegroups.com
Hi,

Ah, not entirely the solution, but you pointed me in the right direction.

class HeaderBlockService extends BaseBlockService 

So, my HeaderBlockService inherits all methods in BaseBlockService, including the method getCacheKeys. The default one uses id and updated_at, but I created an override that used the settings of the block instead, resulting in a key that is the same when it needs to be the same.

Thanks!

Willem

Thomas Rabaix

unread,
Dec 3, 2014, 9:40:40 AM12/3/14
to sonata...@googlegroups.com
Hello,

You need to use the extra_cache_key key settings to overwrite some keys used in the final cache array : https://github.com/sonata-project/SonataBlockBundle/blob/master/Templating/Helper/BlockHelper.php#L329-L332





--
You received this message because you are subscribed to the Google Groups "sonata-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sonata-users...@googlegroups.com.
To post to this group, send email to sonata...@googlegroups.com.
Visit this group at http://groups.google.com/group/sonata-users.
For more options, visit https://groups.google.com/d/optout.



--
Reply all
Reply to author
Forward
0 new messages