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

Services Injector Bundle Laravel Package

devmachine/services-injector-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require devmachine/services-injector-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Devmachine\ServicesInjectorBundle\DevmachineServicesInjectorBundle::class => ['all' => true],
    ];
    
  2. Enable Annotations: Ensure SensioFrameworkExtraBundle is installed and configured (this bundle depends on it). Add to config/packages/framework.yaml:

    framework:
        annotations:
            resource: ['../src/']
            autoload: true
    
  3. First Use Case: Annotate a controller method to inject a service:

    use Devmachine\ServicesInjectorBundle\Annotation\InjectService;
    
    class MyController extends AbstractController
    {
        /**
         * @InjectService("my_service_id")
         */
        public function index(MyServiceInterface $service)
        {
            return $service->doSomething();
        }
    }
    

Implementation Patterns

Common Workflows

  1. Service Injection in Controllers: Use @InjectService on method arguments to auto-wire services:

    /**
     * @InjectService("mailer")
     */
    public function sendWelcomeEmail(MailerInterface $mailer, string $email)
    {
        $mailer->send(...);
    }
    
  2. Combining with Type-Hinting: Leverage Symfony 3.3+ type-hinting for cleaner code:

    public function index(UserRepositoryInterface $users) // Auto-injected if service exists
    {
        // ...
    }
    
  3. Conditional Injection: Use @InjectService with optional parameters:

    /**
     * @InjectService("logger", optional=true)
     */
    public function logAction(?LoggerInterface $logger = null)
    {
        if ($logger) {
            $logger->info("Action triggered");
        }
    }
    
  4. Grouped Services: Inject multiple services at once via @InjectServices (if supported by the bundle):

    /**
     * @InjectServices({
     *     "service1": "service_id_1",
     *     "service2": "service_id_2"
     * })
     */
    public function complexAction(Service1Interface $service1, Service2Interface $service2)
    {
        // ...
    }
    
  5. Integration with DependencyInjection: Define services in config/services.yaml:

    services:
        App\Service\MyService:
            arguments:
                $param: '%env(APP_PARAM)%'
    

    Then inject via annotation:

    /**
     * @InjectService("App\Service\MyService")
     */
    public function myAction(MyService $service)
    {
        // ...
    }
    

Integration Tips

  1. Avoid Mixing Approaches: Stick to either annotations or type-hinting for consistency. Mixing may lead to conflicts.

  2. Prioritize Type-Hinting: Prefer Symfony’s native type-hinting (e.g., public function index(UserRepository $users)) over annotations where possible for maintainability.

  3. Document Custom Services: Annotate custom services in services.yaml with tags or aliases for clarity:

    services:
        App\Service\CustomLogger:
            tags: ['app.logger']
            alias: 'logger.custom'
    

    Then inject via:

    /**
     * @InjectService("logger.custom")
     */
    
  4. Testing: Mock services in tests by overriding the container:

    $container->set('my_service', $mockService);
    
  5. Performance: Cache annotations if the bundle supports it (check config/packages/devmachine_services_injector.yaml for options).


Gotchas and Tips

Pitfalls

  1. Annotation Parsing Order:

    • Annotations are parsed before Symfony’s autowiring. If a service is not found, the bundle may throw an error early in the request lifecycle.
    • Fix: Ensure all required services are defined in services.yaml or loaded via bundles.
  2. Circular Dependencies:

    • Injecting services with circular dependencies (e.g., ServiceA injects ServiceB, which injects ServiceA) will fail silently or throw cryptic errors.
    • Fix: Refactor dependencies or use lazy-loading (e.g., Autowire with lazy: true in services.yaml).
  3. Case Sensitivity:

    • Service IDs in annotations are case-sensitive. "mailer" ≠ "Mailer".
    • Fix: Use consistent naming (e.g., lowercase with underscores).
  4. Override Conflicts:

    • If a service is defined both in services.yaml and via a bundle, the last definition wins. Annotations may not reflect the expected service.
    • Fix: Explicitly alias services or use parent: in services.yaml.
  5. Deprecated Bundle:

    • The bundle is archived and lacks community support. Symfony’s native autowiring (since 3.3) may be a better long-term choice.
    • Fix: Migrate to type-hinting or consider nelmio/cors-bundle for modern alternatives.
  6. Annotation Caching:

    • If annotations aren’t reloaded after changes, old mappings may persist.
    • Fix: Clear cache (php bin/console cache:clear) or use debug:config to verify mappings.

Debugging Tips

  1. Check Service Existence: Run php bin/console debug:container to verify a service ID exists before annotating.

  2. Enable Debug Mode: Set APP_DEBUG=true in .env to see detailed annotation parsing errors.

  3. Log Annotations: Temporarily enable annotation logging in config/packages/devmachine_services_injector.yaml:

    devmachine_services_injector:
        debug: true
    
  4. Inspect Compiled Code: Check var/cache/dev/ for compiled annotation mappings (e.g., appDevDebugProjectContainer.php).

  5. Fallback to Manual Injection: If annotations fail, manually inject services in the constructor:

    public function __construct(private MyService $service) {}
    

Extension Points

  1. Custom Annotations: Extend the bundle by creating a custom annotation (e.g., @InjectScopedService) and hook into the bundle’s event system (if documented).

  2. Service Aliases: Define aliases in services.yaml to simplify injection:

    services:
        App\Service\MyService:
            alias: 'app.my_service'
    

    Then inject via @InjectService("app.my_service").

  3. Dynamic Service Lookup: Use a closure in annotations (if supported) for dynamic service resolution:

    /**
     * @InjectService("service.{{ request.get('type') }}")
     */
    public function dynamicAction($service)
    {
        // ...
    }
    
  4. Integration with Other Bundles: Combine with stof/doctrine-extensions-bundle for ORM-specific services:

    /**
     * @InjectService("stof_doctrine_extensions.softdeleteable.manager")
     */
    
  5. Environment-Specific Services: Use %kernel.environment% in service IDs:

    /**
     * @InjectService("logger.{{ app.env('APP_ENV') }}")
     */
    
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.
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table