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

Systembundle Laravel Package

box4b/systembundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to composer.json:

    "require": {
        "box4b/systembundle": "dev-main"
    }
    

    Run composer update box4b/systembundle.

  2. Register the Bundle In config/bundles.php (Symfony 4.3+):

    return [
        // ...
        box4b\SystemBundle\SystemBundle::class => ['all' => true],
    ];
    

    (For Symfony <4.3, add to AppKernel::registerBundles().)

  3. First Use Case: Cron Job

    • Configure /etc/cron.d/box4bsystem (as per README).
    • Create a listener for CronEvent::EVERY_MINUTE:
      // src/EventListener/CronListener.php
      namespace App\EventListener;
      
      use box4b\SystemBundle\Event\CronEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class CronListener implements EventSubscriberInterface
      {
          public static function getSubscribedEvents()
          {
              return [
                  CronEvent::EVERY_MINUTE => 'onMinute',
              ];
          }
      
          public function onMinute(CronEvent $event)
          {
              // Your logic here (e.g., log, send notifications).
          }
      }
      

Implementation Patterns

Event-Driven Workflows

  1. Cron Jobs

    • Use predefined frequencies (EVERY_MINUTE, EVERY_HOUR) or create custom ones by dispatching events manually:
      $dispatcher->dispatch(new CronEvent(CronEvent::CUSTOM_EVENT, ['key' => 'value']));
      
    • Best Practice: Group related cron tasks into a single listener and use a switch or if-else to handle different frequencies.
  2. Init Scripts (Systemd/Upstart)

    • Dispatch InitEvent::EVENT_START/EVENT_STOP in listeners to perform startup/shutdown tasks (e.g., cache warming, cleanup).
    • Example:
      public function onStart(InitEvent $event)
      {
          // Preload data or initialize services.
      }
      
  3. Integration with Symfony Services

    • Inject services (e.g., Mailer, EntityManager) into listeners:
      use Symfony\Component\Mailer\MailerInterface;
      
      class CronListener {
          public function __construct(private MailerInterface $mailer) {}
      
          public function onMinute(CronEvent $event) {
              $this->mailer->send(...);
          }
      }
      
    • Register the listener as a service in config/services.yaml:
      services:
          App\EventListener\CronListener:
              arguments:
                  $mailer: '@mailer'
      

Advanced Patterns

  • Dynamic Cron Scheduling Use the bundle to trigger jobs dynamically (e.g., via API) by dispatching CronEvent with custom names:

    $dispatcher->dispatch(new CronEvent('api_triggered_job'));
    

    Then listen for 'api_triggered_job' in your subscriber.

  • Logging and Monitoring Log cron/init events with timestamps for debugging:

    public function onMinute(CronEvent $event) {
        \Log::info('Cron job ran at ' . now()->toIso8601String());
    }
    

Gotchas and Tips

Pitfalls

  1. Cron File Permissions

    • Ensure /etc/cron.d/box4bsystem is writable by the cron user (typically root):
      sudo chown root:root /etc/cron.d/box4bsystem
      sudo chmod 644 /etc/cron.d/box4bsystem
      
    • Debugging: Test cron manually with:
      sudo -u [YOUR_USER] /usr/bin/php [PATH_TO_SYMFONY_PROJECT]/app/console box4b:cron --env=prod
      
  2. Event Dispatcher Scope

    • Events are dispatched in the console context. Avoid injecting services that require HTTP (e.g., RequestStack) unless explicitly configured for console.
    • Fix: Use ConsoleApplication or Command services for HTTP-dependent logic.
  3. Time Zone Handling

    • Cron events use the system time zone. Ensure your Symfony app’s time zone (APP_TIMEZONE in .env) matches to avoid scheduling discrepancies.
  4. Init Scripts and Systemd

    • If using systemd, create a service file (e.g., /etc/systemd/system/box4bsystem.service):
      [Unit]
      Description=System Bundle Init Script
      
      [Service]
      ExecStart=/usr/bin/php /path/to/app/console box4b:init start
      ExecStop=/usr/bin/php /path/to/app/console box4b:init stop
      User=[YOUR_USER]
      
    • Reload systemd after changes:
      sudo systemctl daemon-reload
      sudo systemctl enable box4bsystem
      

Debugging Tips

  • Check Event Dispatching Temporarily add a global subscriber to log all events:

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\EventDispatcher\GenericEvent;
    
    class DebugSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [CronEvent::class => 'logEvent'];
        }
    
        public function logEvent(GenericEvent $event) {
            \Log::debug('Event dispatched:', ['event' => $event->getName(), 'data' => $event->getArguments()]);
        }
    }
    
  • Verify Cron Execution Redirect cron output to a log file for debugging:

    * * * * * [YOUR_USER] /usr/bin/php [PATH]/app/console box4b:cron --env=prod >> /var/log/box4b_cron.log 2>&1
    

Extension Points

  1. Custom Event Names Extend the bundle by adding new event constants to CronEvent/InitEvent:

    // In your bundle's Event/CronEvent.php
    const CUSTOM_EVENT = 'custom.event.name';
    

    Then dispatch/listen for these names.

  2. Command Overrides Override the box4b:cron/box4b:init commands in your bundle’s Resources/config/commands.xml:

    <container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
        <services>
            <service id="box4b.system.cron_command" class="App\Command\CustomCronCommand">
                <tag name="console.command" command="box4b:cron" />
            </service>
        </services>
    </container>
    
  3. Environment-Specific Config Use Symfony’s parameter system to customize cron paths/environments:

    # config/packages/box4b_system.yaml
    box4b_system:
        cron_command: '%env(BOX4B_CRON_CMD)%'  # e.g., "php /app/console box4b:cron --env=prod"
    

    Then inject the config into your listeners.

  4. Dependency Injection Bind the EventDispatcher to your listeners via constructor injection (as shown in Implementation Patterns) to avoid null references.

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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui