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

Sonata Block Bundle Laravel Package

awaresoft/sonata-block-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    • Clone the repository into your project’s src/Awaresoft directory and symlink it:
      mkdir -p src/Awaresoft
      git clone [repo-url] src/Awaresoft/SonataBlockBundle
      
    • Remove any existing Composer-installed version (if present) and update autoloader:
      rm -rf vendor/awaresoft/sonata-block-bundle
      composer dump-autoload
      
  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Awaresoft\SonataBlockBundle\SonataBlockBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Create a basic block type (e.g., TextBlock) in src/Entity/Block/TextBlock.php:

    namespace App\Entity\Block;
    
    use Awaresoft\SonataBlockBundle\Model\BlockInterface;
    
    class TextBlock implements BlockInterface {
        private $content;
        // Implement BlockInterface methods (getType(), setSettings(), etc.)
    }
    

    Register it in config/packages/sonata_block.yaml:

    sonata_block:
        blocks:
            text:
                class: App\Entity\Block\TextBlock
                type: text
    
  4. Clear Cache:

    php bin/console cache:clear
    

Implementation Patterns

Core Workflows

  1. Block Creation & Management:

    • Extend Awaresoft\SonataBlockBundle\Model\BlockInterface for custom blocks.
    • Use the BlockManager service to fetch/manage blocks:
      $blockManager = $this->container->get('sonata.block.manager');
      $blocks = $blockManager->getBlocksByContext('admin');
      
  2. Dynamic Block Rendering:

    • Override the block rendering logic in a custom service:
      # config/services.yaml
      services:
          App\Service\CustomBlockRenderer:
              arguments:
                  - '@sonata.block.renderer'
      
      class CustomBlockRenderer extends AbstractRenderer {
          public function renderBlock(BlockInterface $block) {
              // Custom logic
              return $this->renderView('blocks/custom.html.twig', ['block' => $block]);
          }
      }
      
  3. Block Contexts:

    • Define contexts in sonata_block.yaml:
      sonata_block:
          contexts:
              admin: ~
              frontend: ~
      
    • Assign blocks to contexts via the admin panel or programmatically:
      $block->setContext(['admin', 'frontend']);
      
  4. Block Settings:

    • Use setSettings()/getSettings() to store block-specific data:
      $block->setSettings(['color' => 'red']);
      $settings = $block->getSettings();
      
  5. Admin Integration:

    • Enable the Sonata Admin bundle for block management:
      sonata_admin:
          templates:
              layout: 'SonataAdminBundle::standard_layout.html.twig'
      
    • Access the block admin at /admin/block.

Integration Tips

  1. Twig Integration:

    • Embed blocks in templates using:
      {{ render(block) }}
      
    • Pass context-specific blocks:
      {{ render(blocks|render('frontend')) }}
      
  2. Event Listeners:

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

    • Extend the default block table schema in a migration:
      $table->json('settings')->nullable(); // For custom settings
      
  4. Security:

    • Secure block access via voters:
      use Awaresoft\SonataBlockBundle\Security\BlockVoter;
      
      security:
          access_control:
              - { path: ^/admin/block, roles: ROLE_ADMIN }
      

Gotchas and Tips

Pitfalls

  1. Symlink Issues:

    • Forgetting to symlink src/Awaresoft/SonataBlockBundle to the project root or not updating autoload_psr4.php will cause autoloading failures.
    • Fix: Verify symlinks and run composer dump-autoload.
  2. Backward Compatibility:

    • Modifying the bundle directly may break dependent projects. Always test changes in isolation.
    • Tip: Use feature branches and test with composer update awaresoft/sonata-block-bundle@dev.
  3. Cache Invalidation:

    • Changes to block configurations or templates may not reflect until cache is cleared:
      php bin/console cache:pool:clear sonata_block.cache_pool
      
  4. Context Mismatches:

    • Blocks not appearing? Verify contexts are correctly defined in sonata_block.yaml and assigned to blocks.
  5. Database Migrations:

    • Custom block settings may require schema updates. Always back up before migrating.

Debugging

  1. Block Not Rendering:

    • Check if the block is enabled in sonata_block.yaml and assigned to a context.
    • Verify the block class implements BlockInterface fully.
  2. Settings Not Persisting:

    • Ensure setSettings() is called before saving the block entity.
    • Check if the database column for settings exists (e.g., json type in PostgreSQL).
  3. Admin Panel Issues:

    • Clear the Sonata cache:
      php bin/console sonata:cache:clear
      
    • Check for JavaScript errors in the browser console (Sonata Admin relies on JS).

Extension Points

  1. Custom Block Types:

    • Extend Awaresoft\SonataBlockBundle\Block\BaseBlockService for reusable block logic.
  2. Block Renderers:

    • Override Awaresoft\SonataBlockBundle\Renderer\RendererInterface for custom rendering pipelines.
  3. Block Events:

    • Dispatch custom events (e.g., sonata.block.post_save) for post-processing:
      $event = new BlockEvent($block);
      $this->eventDispatcher->dispatch($event, 'sonata.block.post_save');
      
  4. Block Settings Forms:

    • Extend Awaresoft\SonataBlockBundle\Form\Type\BlockSettingsType for custom admin forms.
  5. Block Security:

    • Implement Awaresoft\SonataBlockBundle\Security\BlockInterface for granular permissions.

Pro Tips

  • Use sonata.block.manager to dynamically fetch blocks by context or type:
    $blocks = $blockManager->getBlocksByType('text', 'frontend');
    
  • Leverage Twig Globals to expose blocks in all templates:
    twig:
        globals:
            current_blocks: '@sonata.block.manager'
    
  • Batch Operations: Use the BlockManager to update multiple blocks:
    $blockManager->updateBlocks($blocks, ['context' => ['frontend']]);
    
  • Testing: Mock BlockInterface in PHPUnit:
    $block = $this->createMock(BlockInterface::class);
    $block->method('getType')->willReturn('text');
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware