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

Symfony Laravel Package

berry/symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require berry/symfony
    

    Add the bundle to config/bundles.php:

    return [
        Berry\Symfony\BerrySymfonyBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Rendering a Page Create a controller to render a simple page using the AppLayout from the README:

    // src/Controller/HomeController.php
    use App\View\AppLayout;
    use App\View\IndexPage;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    
    class HomeController extends AbstractController
    {
        public function index(AppLayout $layout, IndexPage $indexPage): Response
        {
            $content = $indexPage->render();
            $html = $layout->render('My App', $content);
            return new Response($html->render());
        }
    }
    
  3. Key Files to Explore

    • src/View/ – Custom view components (e.g., AppLayout.php, IndexPage.php).
    • config/packages/berry_symfony.yaml – Bundle configuration (if any).
    • templates/ – Legacy Twig templates (if migrating from Twig to Berry).

Implementation Patterns

1. View Composition

Use dependency injection to compose views hierarchically:

// src/View/IndexPage.php
class IndexPage
{
    use WithGenerateUrlLocator; // For Symfony URL generation

    public function render(): Element
    {
        return div()
            ->class('content')
            ->text('Welcome to Berry!');
    }
}
  • Pattern: Inject AppLayout into controllers or other views to nest content.

2. Symfony Integration

Leverage Symfony services (e.g., Router, Twig, AssetMapper) via traits:

use Berry\Symfony\Locator\Trait\WithAssetMapperLocator;
use Berry\Symfony\Locator\Trait\WithRouterLocator;

class AppLayout
{
    use WithAssetMapperLocator, WithRouterLocator;

    public function render(string $title, Element $content): Element
    {
        return html()
            ->child(head()
                ->child(title()->text($title))
                ->child(link()
                    ->rel(Rel::Stylesheet)
                    ->href($this->assetMapper->getUrl('css/pico.min.css'))));
    }
}

3. Dynamic Content with Twig-like Logic

Use Berry’s eDSL for dynamic HTML:

// src/View/UserProfile.php
class UserProfile
{
    public function render(string $username, array $posts): Element
    {
        return div()
            ->class('profile')
            ->child(h1()->text("Hello, $username"))
            ->child(ul()->children(
                array_map(fn($post) => li()->text($post), $posts)
            ));
    }
}

4. HTMX and Asset Integration

Embed HTMX or JavaScript dynamically:

// In AppLayout::render()
->child(script()
    ->src($this->assetMapper->getUrl('js/htmx.min.js'))
    ->attr('integrity', '...')
    ->attr('crossorigin', 'anonymous'))

5. Routing with Berry

Generate URLs in views:

// In IndexPage::render()
->child(a()
    ->href($this->generateUrl('app_home'))
    ->text('Home'))

Gotchas and Tips

Pitfalls

  1. No Twig Compatibility Layer

    • Unlike Symfony’s Twig bundle, this package does not translate Twig templates to Berry. You must rewrite templates manually.
    • Workaround: Use a migration script to convert Twig to Berry’s eDSL.
  2. Asset Pipeline Quirks

    • asset() helper (from Symfony’s AssetMapper) may not work out-of-the-box with Berry’s Element structure.
    • Fix: Use WithAssetMapperLocator trait and call $this->assetMapper->getUrl().
  3. Caching Headaches

    • Berry’s Element objects are immutable. Overusing them in loops can bloat memory.
    • Tip: Reuse elements or use ->children() for dynamic lists.
  4. Symfony 6+ Deprecations

    • The package may not support Symfony’s latest features (e.g., AssetMapper changes in Symfony 6.3+).
    • Check: Review the Berry Symfony Bundle’s issues for updates.

Debugging Tips

  • Inspect Elements: Use (new Element())->render() to debug raw HTML output.
  • XDebug Berry: Add ->attr('data-debug', 'true') to elements to inspect attributes.
  • Symfony Profiler: Use dd($element->render()) to dump HTML in controllers.

Extension Points

  1. Custom Elements Extend Berry\Element for domain-specific tags:

    class CardElement extends Element
    {
        public function header(string $text): self
        {
            return $this->child('header')->text($text);
        }
    }
    
  2. Middleware for Berry Add a Kernel event listener to modify responses:

    // src/EventListener/BerryResponseListener.php
    use Symfony\Component\HttpKernel\Event\ResponseEvent;
    
    class BerryResponseListener
    {
        public function onKernelResponse(ResponseEvent $event): void
        {
            $response = $event->getResponse();
            if ($response->headers->get('Content-Type') === 'text/html') {
                $response->setContent(
                    (string) new AppLayout()->render('Modified', div()->text('Hello!')))
                );
            }
        }
    }
    
  3. Testing Views Use PHPUnit to test Element rendering:

    public function testLayoutRendersCorrectly()
    {
        $layout = new AppLayout();
        $html = $layout->render('Test', div()->text('Content'));
        $this->assertStringContainsString('<title>Test</title>', $html->render());
    }
    

Performance Tips

  • Avoid Nested Elements: Flatten structures where possible (e.g., use ->children() instead of deeply nested ->child() calls).
  • Reuse Elements: Cache repeated elements (e.g., navigation bars) as class properties.
  • Lazy-Load Assets: Defer non-critical scripts/styles until after DOMContentLoaded.
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php