nuimarkets / laravel-shared-utils
Common Laravel Classes
Requires
- php: ^8.2
- guzzlehttp/guzzle: ^7.0
- laravel/framework: ^8.0|^9.0|^10.0
- monolog/monolog: ^2.0|^3.0
- sentry/sentry-laravel: ^4.11
- swisnl/json-api-client: ^2.2
Requires (Dev)
- laravel/pint: ^1.0
- mockery/mockery: ^1.4
- orchestra/testbench: ^7.50|^8.0
- phpunit/phpunit: ^9.0
Suggests
- php-amqplib/php-amqplib: Required for RabbitMQ health checks (~3.5.0)
- dev-master
- 0.2.10
- 0.2.9
- 0.2.8
- 0.2.7
- 0.2.6
- 0.2.5
- 0.2.4
- 0.2.3
- 0.2.2
- 0.2.1
- 0.2.0
- 0.1.1
- 0.1.0
- 0.0.27
- 0.0.26
- 0.0.25
- 0.0.24
- 0.0.23
- 0.0.22
- 0.0.21
- 0.0.20
- 0.0.19
- 0.0.18
- 0.0.17
- 0.0.16
- 0.0.15
- 0.0.14
- 0.0.13
- 0.0.12
- 0.0.11
- 0.0.10
- 0.0.9
- 0.0.8
- 0.0.7
- 0.0.6
- 0.0.5
- 0.0.4
- 0.0.3
- 0.0.2
- 0.0.1
- dev-remote_exception
- dev-docs_tidyup
- dev-logging
- dev-fix-add-contract-for-machine-token-binding
- dev-laravel-10-support
- dev-generate_readme
This package is auto-updated.
Last update: 2025-08-04 23:19:10 UTC
README
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), ],
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:
- Fork the repository and create your branch from
master
- Add tests for any new functionality
- Ensure the test suite passes (
composer test-all
) - Follow the existing code style (
composer lint
andcomposer format
) - Update documentation as needed
- 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