Weave 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

Now Bundle Laravel Package

coste/now-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require coste/now-bundle
    

    Add to config/app.php under providers:

    Coste\NowBundle\CosteNowBundle::class,
    
  2. First Use Case Inject the current date directly into a controller:

    use Symfony\Component\HttpFoundation\Request;
    use Coste\NowBundle\Annotation\Now;
    
    class MyController extends AbstractController
    {
        /**
         * @Now()
         */
        public function index(DateTimeInterface $now)
        {
            return $this->json(['current_date' => $now->format('Y-m-d H:i:s')]);
        }
    }
    
  3. Where to Look First

    • Check the GitLab repository for docs.
    • Focus on the @Now annotation and its parameters (e.g., timezone, format).
    • Review Coste\NowBundle\DependencyInjection\Compiler\NowPass.php for extension points.

Implementation Patterns

Common Workflows

  1. Timezone Handling Override the default timezone (UTC) via annotation:

    /**
     * @Now(timezone="Europe/Paris")
     */
    public function index(DateTimeInterface $now) { ... }
    
  2. Date Formatting Return formatted strings directly:

    /**
     * @Now(format="Y-m-d")
     */
    public function getDate(string $formattedNow) { ... }
    
  3. Integration with Symfony Components Combine with other bundles (e.g., SensioFrameworkExtraBundle) for mixed annotations:

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Coste\NowBundle\Annotation\Now;
    
    /**
     * @Route("/date")
     * @Now()
     */
    public function index(DateTimeInterface $now) { ... }
    
  4. Service Injection Inject the NowService manually for reusable logic:

    use Coste\NowBundle\Service\NowService;
    
    public function __construct(private NowService $nowService) {}
    
    public function index() {
        $now = $this->nowService->getNow();
    }
    

Best Practices

  • Avoid Overuse: Reserve @Now for cases where the current time is truly dynamic (e.g., logs, time-sensitive operations). For static dates, use constants or config.
  • Testing: Mock NowService in tests:
    $this->nowService->shouldReceive('getNow')->andReturn(new DateTime('2023-01-01'));
    

Gotchas and Tips

Pitfalls

  1. Annotation Parsing

    • Forgetting to enable annotations in config/packages/sensio_framework_extra.yaml:
      framework:
          validation: { enabled: true }
          router:
              default_uri_generator: router.default
          templating:
              engines: ['twig']
          default_locale: en
          annotations: true  # <-- Critical for @Now to work
      
    • Fix: Ensure sensio_framework_extra is installed and configured.
  2. Circular Dependencies

    • Injecting @Now in services that are also injected into controllers may cause issues if not handled carefully.
    • Fix: Prefer dependency injection over annotations for shared services.
  3. Timezone Ambiguity

    • Defaults to UTC; explicit timezone overrides are required for non-UTC use cases.
    • Fix: Always specify timezone in annotations for clarity.
  4. Performance Overhead

    • @Now creates a new DateTime object per request. For high-traffic endpoints, cache the result if reused:
      $now = $this->nowService->getNow(); // Cache this in a service if needed.
      

Debugging Tips

  • Check Compilation: If @Now is ignored, verify the compiler pass runs:
    php bin/console debug:container --parameters | grep now
    
  • Log Annotations: Enable debug mode to see parsed annotations:
    // In a custom compiler pass or event subscriber
    dump($annotationReader->getMethodAnnotation(new \ReflectionMethod($controller, 'action'), Now::class));
    
  • Override Defaults: Extend the bundle’s configuration via config/packages/coste_now.yaml:
    coste_now:
        default_timezone: 'America/New_York'
        default_format: 'c'
    

Extension Points

  1. Custom Formats Extend the NowService to support custom formatters:

    // src/Service/CustomNowService.php
    class CustomNowService extends NowService {
        public function getCustomFormattedNow(): string {
            return $this->getNow()->format('custom\format');
        }
    }
    

    Bind it in services.yaml:

    services:
        App\Service\CustomNowService: '@Coste\NowBundle\Service\NowService'
    
  2. Event Listeners Trigger actions on time-based events (e.g., daily reports):

    use Symfony\Component\HttpKernel\Event\RequestEvent;
    
    class DailyReportListener {
        public function onKernelRequest(RequestEvent $event) {
            if ($event->isMainRequest() && $this->isDailyReset()) {
                // Trigger logic
            }
        }
    
        private function isDailyReset(): bool {
            return $this->nowService->getNow()->format('Y-m-d') === date('Y-m-d');
        }
    }
    
  3. Database Integration Use @Now to timestamp records:

    /**
     * @Now(format="Y-m-d H:i:s")
     */
    public function createRecord(string $createdAt) {
        $entity->setCreatedAt($createdAt);
        $entityManager->persist($entity);
    }
    
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel