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

Fig Cookies Laravel Package

dflydev/fig-cookies

PSR-7 cookie helper for managing Cookie request headers and Set-Cookie response headers. Provides Cookies and SetCookies collections to read from requests/responses, modify cookie values/attributes, and render updated headers back into PSR-7 messages.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • PSR-7 Compliance: The package is designed for PSR-7 HTTP Message Interface, making it a natural fit for Laravel (which uses PSR-7 via symfony/http-foundation and psr/http-message).
  • Immutable Value Objects: The design aligns with Laravel’s functional programming patterns (e.g., collect(), tap()), reducing side effects.
  • Facade-Based Abstraction: FigRequestCookies and FigResponseCookies simplify cookie manipulation, reducing boilerplate in middleware, controllers, and services.
  • No Session Dependency: Avoids coupling with Laravel’s session system, allowing for standalone cookie management (useful for stateless APIs or hybrid setups).

Integration Feasibility

  • Middleware Integration: Ideal for Laravel middleware (e.g., HandleIncomingCookies, SetOutgoingCookies) to centralize cookie logic.
  • Controller/Service Layer: Can replace manual $request->cookie() or $response->cookie() calls with a more structured API.
  • PSR-7 Middleware: Works seamlessly with Laravel’s PSR-15 middleware (e.g., Psr15Middleware facade) for HTTP toolkit compatibility.
  • Testing: Immutable objects simplify unit testing (e.g., mocking Cookie/SetCookie instances).

Technical Risk

  • Strict Typing (PHP 7.4+): Requires declare(strict_types=1) for full type safety (Laravel 8+ supports this natively).
  • Performance Overhead: Facades introduce minor overhead due to immutable object creation. Mitigate by:
    • Using primitives (Cookie, SetCookie) for performance-critical paths.
    • Caching Cookies/SetCookies instances in middleware.
  • PSR-7 Implementation Quirks: Laravel’s Request/Response may not expose raw headers identically to PSR-7. Verify compatibility with:
    $request->getHeaders()['cookie'] // vs PSR-7 $request->getHeader('Cookie')
    
  • Deprecation Risk: Low (MIT-licensed, actively maintained, no major breaking changes since 2020).

Key Questions

  1. Middleware vs. Facade Tradeoffs:

    • Should cookie logic live in dedicated middleware (e.g., AuthenticateViaCookie) or be scattered via facades in controllers?
    • Recommendation: Use middleware for cross-cutting concerns (e.g., CSRF, auth tokens) and facades for business logic.
  2. Cookie Serialization:

    • How will cookie values (e.g., JSON, encrypted) be handled? The package doesn’t enforce serialization.
    • Recommendation: Pair with symfony/serializer or Laravel’s encrypt() for sensitive data.
  3. SameSite/Partitioned Attributes:

    • Modern browsers require SameSite and Partitioned attributes. The package supports these, but ensure:
      • Laravel’s Response correctly renders headers (test with ->getHeaders()).
      • No conflicts with existing middleware (e.g., ShareErrorsFromSession).
  4. Legacy Code:

    • How will existing $request->cookie() calls transition to FigRequestCookies::get()?
    • Recommendation: Use a wrapper trait or alias during migration:
      trait LegacyCookieCompatibility {
          public function cookie($name, $default = null) {
              return FigRequestCookies::get($this, $name, $default)->getValue();
          }
      }
      
  5. Performance Benchmarking:

    • Measure overhead of facades vs. primitives in high-traffic endpoints (e.g., API rate limiting).
    • Tool: Use laravel-debugbar to compare execution time.

Integration Approach

Stack Fit

  • Laravel Core: Works with:
    • Illuminate\Http\Request (PSR-7 compatible via symfony/http-foundation).
    • Illuminate\Http\Response (PSR-7 via symfony/http-foundation).
    • PSR-15 Middleware: Integrates with Psr15Middleware facade.
  • HTTP Clients: Compatible with:
    • Laravel’s Http client (for outgoing cookies).
    • Guzzle/PSR-18 clients (if used alongside PSR-7).
  • Testing: Plays well with:
    • pestphp/phpunit (mock Cookie/SetCookie).
    • laravel-pint/php-cs-fixer (immutable objects enforce consistency).

Migration Path

  1. Phase 1: Middleware Integration

    • Replace manual cookie parsing in middleware with FigRequestCookies:
      // Before
      $token = $request->cookie('auth_token');
      
      // After
      $token = FigRequestCookies::get($request, 'auth_token')->getValue();
      
    • Add SetCookie logic to response middleware:
      $response = FigResponseCookies::set($response, SetCookie::create('user_prefs')
          ->withValue(json_encode($prefs))
          ->withMaxAge(3600)
      );
      
  2. Phase 2: Controller/Service Layer

    • Replace $request->cookie() with facades in controllers:
      public function updateTheme(Request $request) {
          $theme = FigRequestCookies::get($request, 'theme', 'default')->getValue();
          // ...
      }
      
    • Use modify() for dynamic updates:
      $request = FigRequestCookies::modify($request, 'visits', fn(Cookie $c) =>
          $c->withValue($c->getValue() + 1)
      );
      
  3. Phase 3: Performance Optimization

    • Replace facades with primitives in hot paths:
      // Before (facade)
      $cookies = FigRequestCookies::getAll($request);
      
      // After (primitive)
      $cookies = Cookies::fromRequest($request);
      

Compatibility

  • Laravel Versions:
    • Laravel 8+: Full compatibility (PHP 8.0+, PSR-7).
    • Laravel 7: Works but may require symfony/http-foundation bridge for PSR-7.
    • Laravel 6: Possible but not recommended (PSR-7 support is limited).
  • Dependencies:
    • Requires psr/http-message (Laravel includes this via illuminate/http).
    • No conflicts with Laravel’s cookie() helper (they operate at different layers).
  • Browser/Server Compatibility:
    • Supports modern SameSite/Partitioned attributes (critical for GDPR/CCPA).
    • Test with:
      • Chrome/Firefox/Safari (latest).
      • Legacy browsers (if SameSite=None is required).

Sequencing

  1. Add to composer.json:
    composer require dflydev/fig-cookies
    
  2. Update config/app.php:
    • Ensure Illuminate\Foundation\Providers\FoundationServiceProvider is loaded (for PSR-7).
  3. Write Migration Middleware:
    • Create a CookieMigrationMiddleware to handle legacy $request->cookie() calls.
  4. Test Edge Cases:
    • Empty cookies, malformed headers, SameSite conflicts.
  5. Deploy in Stages:
    • Start with non-critical endpoints (e.g., analytics cookies).
    • Monitor performance with tideways/xhprof or blackfire.io.

Operational Impact

Maintenance

  • Pros:
    • Immutable Design: Reduces bugs from accidental state mutations.
    • Type Safety: Strict typing catches errors early (e.g., non-string cookie values).
    • Decoupled: No dependency on Laravel’s session system.
  • Cons:
    • Boilerplate: Facades hide complexity but may require more code for advanced use cases.
    • Learning Curve: Team must adopt PSR-7 mindset (e.g., treating Request/Response as immutable).
  • Tooling:
    • Use phpstan to enforce type safety.
    • Add phpcs rules to detect anti-patterns (e.g., excessive facade usage).

Support

  • Debugging:
    • Cookie Dumping: Add a dumpCookies() helper:
      function dumpCookies(Request $request) {
          dd(Cookies::fromRequest($request)->all());
      }
      
    • Header Inspection: Log raw Set-Cookie headers:
      $response->getHeaders()['set-cookie'];
      
  • Common Issues:
    • Case Sensitivity: Cookie names are case-insensitive in HTTP but case-sensitive in code. Normalize with strtolower().
    • Encoding: Ensure cookie values are URL-encoded (the package handles this automatically).
    • SameSite Errors: Test with curl -H "Cookie: ..." and browser dev tools.

Scaling

  • Performance:
    • Benchmark: Compare facades vs. primitives in load tests (
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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