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

Laravel Kernel Service Laravel Package

zxf5115/laravel-kernel-service

Laravel package that turns your app kernel into a service layer, helping organize core business logic behind a clean interface. Aims to centralize shared operations, keep controllers thin, and improve maintainability across Laravel projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require zxf5115/laravel-kernel-service
    

    Publish the config file (if available):

    php artisan vendor:publish --provider="Zxf5115\KernelService\KernelServiceServiceProvider"
    
  2. First Use Case: Registering a Kernel Service Define a service in config/kernel-service.php:

    'services' => [
        'example' => [
            'class' => \App\Services\ExampleService::class,
            'singleton' => true,
            'parameters' => [
                'config.key' => 'value',
            ],
        ],
    ],
    

    Bind the service in a service provider (e.g., AppServiceProvider):

    use Zxf5115\KernelService\Facades\KernelService;
    
    public function boot()
    {
        KernelService::register('example');
    }
    
  3. Resolve and Use

    $service = app('example'); // Or via facade
    $result = $service->doSomething();
    

Implementation Patterns

Dependency Injection Workflow

  • Service Registration: Register services in AppServiceProvider@boot or a dedicated provider.
    KernelService::register('serviceName', [
        'class' => \App\Services\MyService::class,
        'singleton' => true,
        'parameters' => ['param1' => 'value1'],
    ]);
    
  • Dynamic Binding: Useful for modular applications where services are loaded conditionally.
    if (config('app.feature_flag')) {
        KernelService::register('conditionalService');
    }
    

Integration with Laravel Ecosystem

  • Service Container: Leverage Laravel’s built-in container for dependency resolution.
    $service = app()->make('serviceName');
    
  • Facades: Use the provided facade for cleaner syntax.
    $result = KernelService::call('serviceName', 'method', [$arg1, $arg2]);
    
  • Configuration: Override defaults via config/kernel-service.php:
    'default_lifetime' => 'P1D', // Default TTL for non-singleton services
    'scopes' => [
        'web' => ['example', 'authService'],
    ],
    

Common Use Cases

  1. Shared Services: Singleton services for caching, logging, or API clients.
    KernelService::register('logger', [
        'class' => \App\Services\Logger::class,
        'singleton' => true,
    ]);
    
  2. Scoped Services: Bind services to specific HTTP scopes (e.g., web, api).
    KernelService::scope('web')->register('sessionHandler');
    
  3. Method Calls: Execute service methods directly.
    $data = KernelService::call('dataService', 'fetch', ['user_id' => 1]);
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies:

    • Avoid circular references between services. Use interfaces or abstract classes for decoupling.
    • Example: If ServiceA depends on ServiceB and vice versa, refactor to introduce a third service or use dependency injection carefully.
  2. Singleton Misuse:

    • Singleton services persist for the entire request lifecycle (or app lifecycle if global). Avoid storing request-specific data.
    • Fix: Use singleton: false for request-scoped services or clear the container manually:
      app()->forgetInstance('serviceName');
      
  3. Configuration Overrides:

    • Changes to config/kernel-service.php require a config cache rebuild:
      php artisan config:cache
      
    • Tip: Use environment variables for dynamic configuration:
      'parameters' => [
          'api_key' => env('SERVICE_API_KEY'),
      ],
      
  4. Facade vs. Container:

    • Facades cache the container resolution. Clear the facade cache if services behave unexpectedly:
      \Illuminate\Support\Facades\Facade::clearResolvedInstance('KernelService');
      

Debugging Tips

  • Service Not Found:

    • Verify the service is registered in config/kernel-service.php or via KernelService::register().
    • Check for typos in service names or class paths.
    • Enable debug mode (APP_DEBUG=true) to see binding errors.
  • Dependency Injection Failures:

    • Use app()->bindings to inspect registered services:
      dd(app()->bindings());
      
    • For parameter resolution issues, ensure all required parameters are provided in the parameters array or are resolvable by the container.

Extension Points

  1. Custom Resolvers:

    • Extend the package by creating a custom resolver for complex dependencies:
      KernelService::extend('custom', function ($app, $parameters) {
          return new \App\Services\CustomService($parameters['param']);
      });
      
    • Register the resolver in the service provider:
      KernelService::resolver('custom', \App\Resolvers\CustomResolver::class);
      
  2. Event Listeners:

    • Listen for service registration events to log or validate services:
      KernelService::registering(function ($name, $config) {
          Log::info("Registering service: {$name}");
      });
      
  3. Middleware Integration:

    • Bind services to HTTP middleware for request-specific initialization:
      KernelService::scope('web')->register('requestService');
      
    • Resolve in middleware:
      public function handle($request, Closure $next) {
          $service = app('requestService');
          return $next($request);
      }
      

Performance Considerations

  • Singleton vs. Non-Singleton:
    • Prefer singletons for stateless services (e.g., API clients, repositories).
    • Use non-singleton services for request-specific operations (e.g., form handlers).
  • Lazy Loading:
    • Defer service initialization until first use by omitting singleton: true and relying on Laravel’s lazy loading:
      KernelService::register('lazyService', [
          'class' => \App\Services\LazyService::class,
          'singleton' => false,
      ]);
      
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.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin