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 Demo Bundle Laravel Package

danielm/symfony-demo-bundle

Demo Symfony bundle showing common bundle features: console command, services/contracts, events/subscriber, Twig extension, controllers with JSON/HTML routes, config with env vars, translations and public assets. Useful as a Symfony Flex recipe/demo reference.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require danielm/symfony-demo-bundle
    

    If not using Flex, manually register the bundle in config/bundles.php:

    return [
        // ...
        DanielM\DemoBundle\DanielMDemoBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Console Command Run the demo command to verify installation:

    php bin/console demo:command
    

    Expected output: Hello from DanielM\DemoBundle\Command\DemoCommand!

  3. First Use Case: Twig Extension Use the demoFcn() Twig function in a template:

    {{ demoFcn() }}
    

    Expected output: Hello from Twig!

  4. First Use Case: Controller Endpoints Test the routes:

    • GET /{a}/{b} → Returns JSON with a + b.
    • GET /view → Renders a Twig template.
    • GET /dispatch/{md5_hash} → Dispatches UnnecessaryEvent (useful for testing events).

Implementation Patterns

Core Workflows

  1. Service Contracts/Adapters

    • Implement DemoServiceInterface in your own service:
      use DanielM\DemoBundle\Service\DemoServiceInterface;
      
      class MyService implements DemoServiceInterface {
          public function doSomething(string $input): string {
              return "Processed: $input";
          }
      }
      
    • Register it as a service in services.yaml:
      services:
          DanielM\DemoBundle\Service\DemoServiceInterface: '@my_service'
      
  2. Events and Subscribers

    • Dispatch events in controllers or services:
      $event = new UnnecessaryEvent($data);
      $this->eventDispatcher->dispatch($event);
      
    • Subscribe to events by extending DemoSubscriber or creating a new subscriber:
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      use DanielM\DemoBundle\Event\UnnecessaryEvent;
      
      class MySubscriber implements EventSubscriberInterface {
          public static function getSubscribedEvents(): array {
              return [
                  UnnecessaryEvent::class => 'onUnnecessaryEvent',
              ];
          }
      
          public function onUnnecessaryEvent(UnnecessaryEvent $event) {
              // Handle event logic
          }
      }
      
  3. Configuration

    • Access bundle config in services:
      $this->container->getParameter('danielm_demo.sample_config');
      
    • Override defaults via config/packages/danielm_demo.yaml:
      danielm_demo:
          sample_config: 'custom_value'
          sample_env: '%env(DEMO_SAMPLE_ENV)%'
      
  4. Twig Extensions

    • Extend DemoTwigExtension or create a new extension:
      use Twig\Extension\AbstractExtension;
      use Twig\TwigFunction;
      
      class MyTwigExtension extends AbstractExtension {
          public function getFunctions(): array {
              return [
                  new TwigFunction('myCustomFunction', [$this, 'customFunction']),
              ];
          }
      
          public function customFunction(): string {
              return "Custom Twig Output";
          }
      }
      
  5. Assets and Translations

    • Load assets via assets/ directory (Symfony Flex auto-registers them).
    • Use translations in templates:
      {{ 'demo.message'|trans }}
      
    • Override translations in translations/messages.en.yaml:
      demo:
          message: "Custom translated message"
      

Integration Tips

  1. Dependency Injection

    • Prefer constructor injection for services:
      public function __construct(private DemoServiceInterface $demoService) {}
      
  2. Testing

    • Mock the bundle’s services in PHPUnit:
      $this->container->set(DemoServiceInterface::class, $this->createMock(DemoServiceInterface::class));
      
  3. Flex Recipes

    • Extend the bundle’s recipe for custom behavior (see blog post).
  4. Environment Variables

    • Use .env for sensitive/configurable values:
      DEMO_SAMPLE_ENV=custom_value
      

Gotchas and Tips

Pitfalls

  1. Event Dispatching

    • Events like UnnecessaryEvent are not automatically dispatched. You must manually trigger them in your code.
    • Avoid overusing events for simple logic; prefer direct method calls.
  2. Configuration Overrides

    • If danielm_demo.yaml is missing, Symfony will throw a ParameterNotFoundException. Ensure the file exists even if empty:
      # config/packages/danielm_demo.yaml
      danielm_demo: {}
      
  3. Twig Auto-Reloading

    • Twig extensions require a cache clear after changes:
      php bin/console cache:clear
      
  4. Console Command Naming

    • Commands like demo:command are not auto-discovered in Laravel (this is a Symfony bundle). In Laravel, use:
      php artisan demo:command
      
      Or register it via App\Providers\CommandServiceProvider.
  5. Route Conflicts

    • The bundle’s routes (/{a}/{b}, /view, etc.) may conflict with existing routes. Prefix them in config/routes.yaml:
      danielm_demo:
          resource: "@DanielMDemoBundle/Resources/config/routes.yaml"
          prefix: "/demo"
      

Debugging Tips

  1. Check Event Subscribers

    • Verify subscribers are registered:
      php bin/console debug:event-dispatcher
      
    • Look for UnnecessaryEvent in the output.
  2. Inspect Service Bindings

    • List all services to debug DI:
      php bin/console debug:container | grep DemoService
      
  3. Environment Variables

    • Validate .env values:
      php bin/console debug:config danielm_demo
      
  4. Twig Debugging

    • Enable Twig debug mode in config/packages/twig.yaml:
      twig:
          debug: '%kernel.debug%'
          strict_variables: '%kernel.debug%'
      

Extension Points

  1. Add New Services

    • Extend DemoServiceInterface or create new interfaces in your own bundle.
  2. Custom Events

    • Create new events by extending Symfony\Component\EventDispatcher\Event:
      class MyCustomEvent extends Event {
          public function __construct(private string $data) {}
          public function getData(): string { return $this->data; }
      }
      
  3. Override Twig Functions

    • Replace DemoTwigExtension by binding your own extension:
      # config/services.yaml
      services:
          Twig\Extension\DemoTwigExtension: '@my_custom_twig_extension'
      
  4. Modify Console Commands

    • Extend DemoCommand or create a new command:
      use Symfony\Component\Console\Command\Command;
      use Symfony\Component\Console\Input\InputInterface;
      use Symfony\Component\Console\Output\OutputInterface;
      
      class MyCommand extends Command {
          protected function execute(InputInterface $input, OutputInterface $output): int {
              $output->writeln('Custom command output');
              return Command::SUCCESS;
          }
      }
      
  5. Asset Customization

    • Override bundle assets by copying files from vendor/danielm/demo-bundle/Resources/public to public/bundles/danielm_demo.

Laravel-Specific Notes

  1. Bundle Registration

    • In Laravel, register the bundle in config/app.php under extra.bundles.php:
      'bundles' => [
          DanielM\DemoBundle\DanielMDemoBundle::class => true,
      ],
      
  2. Route Prefixing

    • Prefix routes in routes/web.php:
      Route::prefix('demo')->group(function () {
          // Laravel routes here (avoid conflicts with Symfony routes)
      });
      
  3. Service Container Integration

    • Bind Symfony services to Laravel’s container in AppServiceProvider:
      public function register() {
          $this->app->singleton(DemoServiceInterface::class, function ($app) {
              return new MyService();
          });
      }
      
  4. Event Dispatcher

    • Use Laravel’s event system alongside Symfony’s:
      use Symfony\Component\EventDispatcher\EventDispatcherInterface;
      
      $dispatcher = $this->app->make(EventDispatcherInterface::class);
      $dispatcher->dispatch(new
      
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