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

Content Block Bundle Laravel Package

austral/content-block-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require austral/content-block-bundle

Ensure Austral\ContentBlockBundle\AustralContentBlockBundle is registered in config/bundles.php.

  1. Database Migration Run migrations to create the required tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  2. First Content Block Create a custom block type by extending Austral\ContentBlockBundle\Entity\ContentBlockInterface and implementing the required methods. Example:

    namespace App\Entity;
    
    use Austral\ContentBlockBundle\Entity\ContentBlockInterface;
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class CustomBlock implements ContentBlockInterface
    {
        #[ORM\Column(type: 'string', length: 255)]
        private string $title;
    
        #[ORM\Column(type: 'text')]
        private string $content;
    
        // Implement required methods from ContentBlockInterface
        public function getType(): string { return 'custom_block'; }
        public function getContent(): string { return $this->content; }
        // ... other methods
    }
    
  3. Register Block Type Add your block type to the bundle’s configuration in config/packages/austral_content_block.yaml:

    austral_content_block:
        block_types:
            custom_block: App\Entity\CustomBlock
    
  4. Admin Integration The bundle includes a CRUD interface for managing blocks. Access it via /admin/content-blocks (adjust route if needed).


First Use Case: Adding a Hero Section

  1. Create a Block Entity Extend ContentBlockInterface for a hero section:

    class HeroBlock implements ContentBlockInterface
    {
        #[ORM\Column(type: 'string', length: 255)]
        private string $heading;
    
        #[ORM\Column(type: 'string', length: 255, nullable: true)]
        private ?string $subheading;
    
        #[ORM\Column(type: 'string', length: 255)]
        private string $backgroundImage;
    
        // Implement ContentBlockInterface methods
        public function getType(): string { return 'hero'; }
        public function getContent(): string { return json_encode([...]); }
    }
    
  2. Render the Block in Twig Use the content_block Twig function to render blocks in templates:

    {% for block in blocks %}
        {% if block.type == 'hero' %}
            <section class="hero">
                <h1>{{ block.heading }}</h1>
                <img src="{{ block.backgroundImage }}" alt="{{ block.heading }}">
            </section>
        {% endif %}
    {% endfor %}
    
  3. Fetch Blocks in Controller Retrieve blocks via the ContentBlockRepository:

    use Austral\ContentBlockBundle\Repository\ContentBlockRepository;
    
    public function showHomepage(ContentBlockRepository $blockRepo)
    {
        $heroBlocks = $blockRepo->findBy(['type' => 'hero']);
        return view('homepage', compact('heroBlocks'));
    }
    

Implementation Patterns

Workflow: Dynamic Page Composition

  1. Define Block Types Create modular block entities (e.g., FeatureBlock, TestimonialBlock, CTABlock) for reusable components.

  2. Admin Management Use the built-in admin interface to create, edit, and organize blocks. Leverage the Library feature (v3.1+) to manage blocks across multiple domains:

    austral_content_block:
        library:
            enabled: true
            domains:
                - '*.example.com'
                - '*.client-site.com'
    
  3. Twig Integration Use the content_block Twig function to render blocks dynamically:

    {% for block in blocks %}
        {% include ['@AustralContentBlock/blocks/' ~ block.type ~ '.html.twig', 'blocks/default.html.twig'] %}
    {% endfor %}
    
    • Override default templates in templates/AustralContentBlock/blocks/.
  4. Caching Cache rendered blocks or block collections to improve performance:

    $cachedBlocks = Cache::remember("blocks_{$pageId}", 3600, function() use ($blockRepo) {
        return $blockRepo->findBy(['page' => $pageId]);
    });
    

Integration Tips

  1. Form Handling Use Austral\FormBundle to create custom forms for block types. Example:

    use Austral\FormBundle\Form\Type\AustralFormType;
    
    class HeroBlockType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('heading', TextType::class)
                ->add('subheading', TextType::class, ['required' => false])
                ->add('backgroundImage', AustralFormType::class, [
                    'type' => 'media',
                    'label' => 'Background Image',
                ]);
        }
    }
    

    Register the form type in config/packages/austral_content_block.yaml:

    austral_content_block:
        block_types:
            hero:
                form_type: App\Form\Type\HeroBlockType
    
  2. Event Listeners Extend functionality with events. Example: Log block creation:

    use Austral\ContentBlockBundle\Event\ContentBlockEvents;
    use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
    
    #[AsEventListener(event: ContentBlockEvents::POST_CREATE, method: 'onBlockCreate')]
    public function onBlockCreate(ContentBlockEvent $event)
    {
        $block = $event->getBlock();
        \Log::info("Block created: {$block->getType()}", ['block_id' => $block->getId()]);
    }
    
  3. API Exposure Expose blocks via API using Symfony’s Serializer:

    use Symfony\Component\Serializer\Annotation\Groups;
    
    class HeroBlock implements ContentBlockInterface
    {
        #[Groups(['api'])]
        public function getHeading(): string { return $this->heading; }
    
        #[Groups(['api'])]
        public function getBackgroundImage(): string { return $this->backgroundImage; }
    }
    

    Configure serialization groups in config/packages/api_platform.yaml:

    api_platform:
        formats:
            jsonld:
                mime_types: ['application/ld+json']
                jsonld_contexts:
                    blocks: ['/api/contexts/blocks.jsonld']
    
  4. Multi-Language Support Use Austral\ToolsBundle for translations. Example:

    #[ORM\Column(type: 'json')]
    private array $translations = [];
    
    public function getTranslatedContent(string $locale): string
    {
        return $this->translations[$locale]['content'] ?? $this->content;
    }
    

Gotchas and Tips

Pitfalls

  1. Block Type Registration

    • Issue: Forgetting to register a custom block type in austral_content_block.yaml will cause the admin interface to ignore it.
    • Fix: Always declare block types in the config:
      austral_content_block:
          block_types:
              custom_block: App\Entity\CustomBlock
      
  2. Content Serialization

    • Issue: Storing complex data (e.g., nested objects) directly in getContent() may break rendering or cause serialization errors.
    • Fix: Use JSON encoding/decoding for complex data:
      public function getContent(): string { return json_encode($this->complexData); }
      public function setContent(string $content): void { $this->complexData = json_decode($content, true); }
      
  3. Admin Permissions

    • Issue: The admin interface may not appear if Austral\FormBundle or Austral\ToolsBundle are misconfigured.
    • Fix: Ensure all required bundles are installed and configured:
      composer require austral/form-bundle austral/tools-bundle
      
  4. Database Schema Changes

    • Issue: Adding new fields to block entities after initial migration requires a new migration and potential data migration.
    • Fix: Use Doctrine’s make:entity and make:migration commands:
      php bin/console make:entity --regenerate Austral/ContentBlockBundle/Entity/ContentBlock
      php bin/console make:migration
      
  5. Circular Dependencies

    • Issue: Blocks referencing each other (e.g., a GalleryBlock containing ImageBlock instances) can cause infinite loops in rendering.
    • Fix: Use lazy-loading or DTOs for rendering:
      public function getGalleryImages(): array
      {
          return $this->imageBlocks->map(fn($block) => $block->getImageUrl());
      }
      

Debugging Tips

  1. Check Block Events Enable debug mode to inspect dispatched events:
    #[AsEventListener(event: ContentBlockEvents::PRE_SAVE, method: 'onPreSave')]
    public function onPreSave(ContentBlockEvent
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor