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

Laravel Page Speed Laravel Package

renatomarinho/laravel-page-speed

View on GitHub
Deep Wiki
Context7

Getting Started

The VinkiusLabs/LaravelPageSpeed package optimizes Laravel applications for performance, particularly focusing on API responses, health checks, and asset delivery. To get started:

  1. Installation: Require the package via Composer:
    composer require vinkiuslabs/laravel-page-speed
    
  2. Publish Config: Run php artisan vendor:publish --provider="VinkiusLabs\LaravelPageSpeed\ServiceProvider" to customize settings (e.g., compression, caching).
  3. First Use Case: Enable API response compression by adding the middleware to your app/Http/Kernel.php:
    protected $middleware = [
        \VinkiusLabs\LaravelPageSpeed\Http\Middleware\ApiResponseCompression::class,
    ];
    
  4. Verify: Use the ApiHealthCheck middleware to monitor performance metrics:
    Route::get('/health', \VinkiusLabs\LaravelPageSpeed\Http\Middleware\ApiHealthCheck::class);
    
    Check the response for formatted byte sizes (now supporting TB via the new FormatsBytes trait).

Implementation Patterns

Core Workflows

  1. Response Optimization:

    • Compression: Automatically compresses API responses (JSON/XML) using ApiResponseCompression. Configure thresholds in config/laravel-page-speed.php (e.g., min_bytes_to_compress).
    • Caching: Leverage ElideAttributes to strip unnecessary HTML attributes (e.g., disabled, selected) from cached views:
      use VinkiusLabs\LaravelPageSpeed\Traits\ElideAttributes;
      class MyController {
          use ElideAttributes;
          public function index() {
              return $this->elideAttributes(view('my.view'));
          }
      }
      
  2. Performance Monitoring:

    • Headers: Use ApiPerformanceHeaders to add X-Response-Time and Content-Length headers. The formatBytes() method (now via FormatsBytes trait) supports B, KB, MB, GB, TB:
      $size = 1500000000; // 1.5 GB
      echo formatBytes($size); // Output: "1.5 GB"
      
    • Health Checks: Integrate ApiHealthCheck into routes to expose performance metrics:
      Route::middleware(ApiHealthCheck::class)->group(function () {
          Route::get('/metrics', [MetricsController::class, 'index']);
      });
      
  3. CSS/JS Optimization:

    • Inline CSS: Use InlineCss to inline critical CSS in Octane/Swoole environments (note: static counter behavior is documented for these setups):
      use VinkiusLabs\LaravelPageSpeed\Traits\InlineCss;
      class MyController {
          use InlineCss;
          public function show() {
              return $this->inlineCss(view('home'), ['styles.css']);
          }
      }
      
  4. Comment Removal:

    • Deprecated: Avoid removeSingleLineCommentFromLine() (marked @deprecated). Use removeSingleLineCommentsFromContent() instead:
      use VinkiusLabs\LaravelPageSpeed\Traits\RemoveComments;
      $cleanedContent = removeSingleLineCommentsFromContent($phpFileContent);
      

Integration Tips

  • Middleware Stacking: Combine middlewares for layered optimization:
    protected $middlewareGroups = [
        'web' => [
            \VinkiusLabs\LaravelPageSpeed\Http\Middleware\ApiResponseCompression::class,
            \VinkiusLabs\LaravelPageSpeed\Http\Middleware\ElideAttributes::class,
        ],
    ];
    
  • Testing: Use the package’s 262+ tests as a reference for edge cases (e.g., large file handling, regex attribute matching).

Gotchas and Tips

Pitfalls

  1. Deprecations:

    • removeSingleLineCommentFromLine() is deprecated. Update calls to removeSingleLineCommentsFromContent() to avoid runtime warnings.
    • Symfony/Queue Imports: Removed in v4.4.4 (dead code), but ensure no custom code relies on these.
  2. Regex Overmatching:

    • The ElideAttributes trait’s regex for disabled/selected attributes was simplified. If you extended this trait, verify your custom logic still works.
  3. Octane/Swoole:

    • InlineCss uses a static counter for performance. In Octane, this may behave differently than in traditional PHP-FPM. Test thoroughly in your deployment environment.
  4. Byte Formatting:

    • formatBytes() now includes TB (previously capped at GB). If your app expects GB as the max, update display logic or config thresholds.

Debugging

  • Compression Issues: Check min_bytes_to_compress in config. Set to 0 to compress all responses (not recommended for production).
  • Health Check Metrics: Use dd() on the ApiHealthCheck response to inspect raw data before formatting:
    Route::get('/debug-health', function () {
        $check = new \VinkiusLabs\LaravelPageSpeed\Http\Middleware\ApiHealthCheck();
        dd($check->handle(new Request(), function () {}));
    });
    

Extension Points

  1. Custom Traits:
    • Extend FormatsBytes to add new units (e.g., PB) or locales:
      use VinkiusLabs\LaravelPageSpeed\Traits\FormatsBytes;
      class MyFormatter {
          use FormatsBytes;
          protected $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
      }
      
  2. Middleware Logic:
    • Override ApiResponseCompression to add pre-compression hooks:
      class CustomCompression extends ApiResponseCompression {
          public function handle($request, Closure $next) {
              $response = parent::handle($request, $next);
              // Custom logic here
              return $response;
          }
      }
      
  3. Testing:
    • Mock the FormatsBytes trait for unit tests:
      $formatter = $this->getMockForTrait(FormatsBytes::class);
      $formatter->method('formatBytes')->willReturn('Mocked Size');
      

Config Quirks

  • Caching: The package doesn’t cache responses by default. For persistent caching, integrate with Laravel’s cache system or use Response::cache().
  • Gzip/Brotli: ApiResponseCompression uses Laravel’s built-in compression. Ensure your server supports these algorithms (e.g., .htaccess for Apache).
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi