Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Block Bundle Laravel Package

sonata-project/block-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sonata-project/block-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Sonata\BlockBundle\SonataBlockBundle::class => ['all' => true],
    ];
    
  2. Database Setup: Run migrations to create the block and block_position tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Block: Create a simple block service (e.g., app/Blocks/HelloBlock.php):

    namespace App\Blocks;
    
    use Sonata\BlockBundle\Block\BlockContextInterface;
    use Sonata\BlockBundle\Block\BaseBlockService;
    use Sonata\BlockBundle\Model\BlockInterface;
    
    class HelloBlock extends BaseBlockService
    {
        public function execute(BlockContextInterface $blockContext, BlockInterface $block)
        {
            return ['content' => 'Hello, World!'];
        }
    
        public function getName()
        {
            return 'app.hello_block';
        }
    }
    
  4. Register Service: Add to config/services.yaml:

    services:
        App\Blocks\HelloBlock:
            tags:
                - { name: sonata.block }
    
  5. Enable in Admin: Add to config/packages/sonata_block.yaml:

    sonata_block:
        blocks:
            app_hello_block: ~
    

First Use Case

Use the Sonata Admin dashboard to drag-and-drop the Hello Block onto a page. Verify it renders in the frontend.


Implementation Patterns

Common Workflows

1. Creating Custom Blocks

  • Service-Based Blocks: Extend BaseBlockService for reusable blocks.
    class CustomBlock extends BaseBlockService
    {
        public function execute(BlockContextInterface $blockContext, BlockInterface $block)
        {
            $settings = $block->getSettings();
            return ['data' => $settings['custom_data']];
        }
    }
    
  • Template-Based Blocks: Use BaseBlockService with a Twig template:
    class TemplateBlock extends BaseBlockService
    {
        protected function getTemplate()
        {
            return '@App/Blocks/template_block.html.twig';
        }
    }
    

2. Dynamic Blocks

  • Fetch data dynamically in execute():
    public function execute(BlockContextInterface $blockContext, BlockInterface $block)
    {
        $posts = $this->entityManager->getRepository(Post::class)->findLatest();
        return ['posts' => $posts];
    }
    
  • Pass data to Twig:
    {% for post in block.posts %}
        <h3>{{ post.title }}</h3>
    {% endfor %}
    

3. Block Settings

  • Define settings in configureSettings():
    protected function configureSettings(BaseBlockSettings $settings)
    {
        $settings
            ->set('title', 'Title')
            ->set('custom_data', 'Custom Data', 'text');
    }
    
  • Access settings in execute():
    $title = $block->getSetting('title');
    

4. Caching

  • Enable caching for performance:
    # config/packages/sonata_block.yaml
    sonata_block:
        cache:
            default_lifetime: 3600  # 1 hour
    
  • Override cache lifetime per block:
    public function execute(BlockContextInterface $blockContext, BlockInterface $block)
    {
        return $this->renderView(
            '@App/Blocks/cache_block.html.twig',
            ['data' => $data],
            $blockContext->getCacheLifetime()
        );
    }
    

5. Block Context

  • Use BlockContextInterface to access:
    • Current page ($blockContext->getPage()).
    • Request ($blockContext->getRequest()).
    • Cache ($blockContext->getCache()).

Integration Tips

Frontend Integration

  • Render blocks in Twig:
    {{ render(block) }}
    
  • Pass additional context:
    {{ render(block, {'extra_var': 'value'}) }}
    

Admin Integration

  • Group blocks in the admin panel:
    sonata_block:
        groups:
            custom_group:
                label: 'Custom Blocks'
                blocks:
                    - app_custom_block
    

Event-Driven Extensions

  • Listen to block events (e.g., sonata.block.pre_render):
    // config/services.yaml
    App\EventListener\BlockListener:
        tags:
            - { name: kernel.event_listener, event: sonata.block.pre_render, method: onPreRender }
    

Gotchas and Tips

Pitfalls

  1. Caching Issues:

    • Blocks may not update immediately due to caching. Clear cache after changes:
      php bin/console cache:clear
      
    • Use cache:pool:clear for specific pools if needed.
  2. Block Settings Persistence:

    • Ensure BlockInterface is properly saved after updating settings:
      $block->setSetting('key', 'value');
      $this->blockManager->save($block);
      
  3. Dependency Injection:

    • Avoid circular dependencies when injecting services into blocks. Use lazy loading or interfaces.
  4. Twig Template Paths:

    • Ensure templates are in the correct location (e.g., @App/Blocks/block_name.html.twig). Use getTemplate() in BaseBlockService for clarity.
  5. Database Schema Changes:

    • Migrations for block and block_position tables are required. Always run migrations after updating the bundle.

Debugging Tips

  1. Log Block Execution:

    • Add debug logs in execute():
      $this->logger->debug('Block executed', ['block_id' => $block->getId()]);
      
  2. Check Block Settings:

    • Dump settings in execute() to verify data:
      dump($block->getSettings());
      
  3. Verify Block Registration:

    • Ensure the block service is tagged correctly in services.yaml:
      tags:
          - { name: sonata.block, context: { name: app_custom_block } }
      
  4. Clear Cache After Changes:

    • Always clear cache when:
      • Adding/removing blocks.
      • Changing block settings or templates.
      • Updating the bundle version.

Extension Points

  1. Custom Block Types:

    • Extend BaseBlockService or create a custom block class for unique functionality.
  2. Block Managers:

    • Override the default block manager (Sonata\BlockBundle\Manager\BlockManager) for custom logic.
  3. Block Storage:

    • Replace the default BlockRepository with a custom implementation for advanced storage needs.
  4. Block Events:

    • Dispatch custom events for block lifecycle management:
      $event = new BlockEvent($block);
      $this->eventDispatcher->dispatch($event, 'sonata.block.custom_event');
      
  5. Block Security:

    • Add security checks in execute():
      if (!$this->security->isGranted('ROLE_VIEW_BLOCK', $block)) {
          throw new AccessDeniedException();
      }
      

Configuration Quirks

  1. Default Block Settings:

    • Set default settings in configureSettings():
      $settings->setDefault('title', 'Default Title');
      
  2. Block Visibility:

    • Control block visibility via isVisible():
      public function isVisible(BlockContextInterface $blockContext, BlockInterface $block)
      {
          return $blockContext->getRequest()->get('show_block', false);
      }
      
  3. Block Ordering:

    • Use getPosition() and setPosition() to manage block order dynamically.
  4. Multi-Site Support:

    • Extend the Block entity to include site-specific fields if using multi-site setups.
  5. Block Inheritance:

    • Use BlockContextInterface to inherit settings from parent blocks in nested layouts.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui