nuimarkets/laravel-shared-utils

Common Laravel Classes

0.2.10 2025-08-04 23:18 UTC

README

Latest Version PHP Version Laravel Version Tests License

A comprehensive Laravel package providing standardized components for building robust microservice architectures. Battle-tested in production environments handling millions of requests.

Quick Start

composer require nuimarkets/laravel-shared-utils
// Enable distributed tracing in 2 minutes
class MyRequestLogger extends RequestLoggingMiddleware {
    protected function addServiceContext($request, $context) {
        $context['service_name'] = 'my-service';
        return $context;
    }
}

// Add comprehensive health checks instantly
Route::get('/healthcheck', [HealthCheckController::class, 'check']);

Key Features

Distributed Tracing

Native AWS X-Ray integration with automatic trace propagation across microservices. Track requests through your entire service mesh with zero configuration.

Advanced Logging

Production-ready logging with automatic Elasticsearch routing, sensitive data redaction, and structured JSON formatting. Fixes common logging issues that cause logs to end up in wrong indexes.

Health Monitoring

Comprehensive health checks for MySQL, PostgreSQL, Redis, RabbitMQ, storage, cache, and PHP environment. Get detailed diagnostics with a single endpoint.

Service Communication

Enhanced RemoteRepository with retry logic, performance monitoring, intelligent caching, and automatic JWT authentication for service-to-service calls.

Analytics Integration

Complete Intercom integration for user analytics and event tracking with queue-based processing and multi-tenant support.

Testing Utilities

Automated test database management, specialized test jobs for queue testing, and base test cases for rapid test development.

Requirements

  • PHP 8.0 or higher
  • Laravel 8.x, 9.x, or 10.x
  • Composer 2.x

Installation

composer require nuimarkets/laravel-shared-utils

Optional Configuration Publishing

# Publish all configs
php artisan vendor:publish --provider="NuiMarkets\LaravelSharedUtils\Providers\LoggingServiceProvider"

# Publish specific configs
php artisan vendor:publish --tag=logging-utils-config
php artisan vendor:publish --tag=intercom-config

Documentation

Core Components

Component Description Documentation
Distributed Tracing AWS X-Ray integration with request correlation Guide
Logging System Enhanced logging with Elasticsearch routing Guide
RemoteRepository Service-to-service communication framework Guide
Intercom Integration User analytics and event tracking Guide
IncludesParser API response optimization utility Guide

Quick Examples

Enable Distributed Tracing

// 1. Extend RequestLoggingMiddleware
class ServiceRequestLogger extends RequestLoggingMiddleware {
    protected function addServiceContext($request, $context) {
        $context['service_name'] = 'auth-service';
        return $context;
    }
}

// 2. Register in Kernel.php
protected $middleware = [
    \App\Http\Middleware\ServiceRequestLogger::class,
];

// 3. Service calls automatically propagate traces
$this->productRepository->findByIds($productIds);
// Headers automatically include X-Amzn-Trace-Id

Configure Logging

// 1. Create service-specific LogFields
class OrderLogFields extends LogFields {
    const ORDER_ID = 'order_id';
    const ORDER_STATUS = 'order_status';
}

// 2. Configure Monolog
class CustomizeMonoLog extends BaseCustomizeMonoLog {
    protected function createTargetProcessor() {
        return new AddTargetProcessor('order-service');
    }
}

// 3. Logs automatically route to correct Elasticsearch index
Log::info('Order processed', ['order_id' => $order->id]);

Add Health Checks

// Routes automatically available at /healthcheck
Route::get('/healthcheck', [HealthCheckController::class, 'check']);

// Response includes all infrastructure status
{
    "status": "healthy",
    "checks": {
        "database": {"status": "up", "response_time": "5ms"},
        "cache": {"status": "up", "driver": "redis"},
        "queue": {"status": "up", "jobs_pending": 0}
    }
}

Architecture

This package follows a trait-based architecture allowing you to:

  • Use only the components you need
  • Extend base classes for customization
  • Integrate gradually into existing codebases

No Service Provider Required

The package intentionally doesn't auto-register a service provider, giving you full control over which components to use.

Cross-Version Compatibility

Laravel PHP Monolog Orchestra Testbench
8.x 8.0+ 2.x 7.x
9.x 8.0+ 2.x 7.x
10.x 8.1+ 3.x 8.x

Configuration

Environment Variables

# Distributed Tracing (automatic with X-Ray)
# No configuration needed!

# Logging
LOG_TARGET=my-service
APP_DEBUG=true

# RemoteRepository
API_GATEWAY_ENDPOINT=https://api.example.com
REMOTE_REPOSITORY_MAX_URL_LENGTH=2048
REMOTE_REPOSITORY_LOG_REQUESTS=true

# Intercom
INTERCOM_ENABLED=true
INTERCOM_TOKEN=your_token
INTERCOM_SERVICE_NAME=my-service

RemoteRepository Configuration

Add to your config/app.php:

'remote_repository' => [
    'base_uri' => env('API_GATEWAY_ENDPOINT'),
    'max_url_length' => env('REMOTE_REPOSITORY_MAX_URL_LENGTH', 2048),
    'log_requests' => env('REMOTE_REPOSITORY_LOG_REQUESTS', true),
],

See full migration guide →

Testing

# Run all tests
composer test-all

# Run specific tests
composer test RequestMetrics

# Generate coverage report
composer test-coverage

# Code quality
composer lint    # Check code style
composer format  # Fix code style

Contributing

We welcome contributions! Please follow these guidelines:

  1. Fork the repository and create your branch from master
  2. Add tests for any new functionality
  3. Ensure the test suite passes (composer test-all)
  4. Follow the existing code style (composer lint and composer format)
  5. Update documentation as needed
  6. Submit a pull request with a clear description of changes

Performance Impact

  • Distributed Tracing: < 1ms overhead per request
  • Logging: Asynchronous processing, no request blocking
  • Health Checks: Cached results available, configurable timeouts
  • RemoteRepository: Built-in caching reduces API calls by up to 80%

Security

  • Automatic redaction of sensitive data in logs
  • JWT token validation for service-to-service communication
  • Environment-aware security settings
  • No credentials stored in code

License

The MIT License (MIT). See License File for more information.

Support

Built with ❤️ by Nui Markets