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

Injection Bundle Laravel Package

astina/injection-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer:

    composer require astina/injection-bundle:dev-master
    

    Enable the bundle in app/AppKernel.php:

    new Astina\Bundle\InjectionBundle\AstinaInjectionBundle(),
    
  2. First Use Case: Inject a service or parameter into a controller using annotations. For example, inject the session service and a parameter acme_foo:

    use Astina\Bundle\InjectionBundle\Annotation as Inject;
    
    class DefaultController
    {
        /**
         * @Inject\Service("session")
         * @var SessionInterface
         */
        private $session;
    
        /**
         * @Inject\Parameter("acme_foo")
         */
        private $foo;
    
        public function indexAction()
        {
            $foo = $this->session->get($this->foo);
            return ['foo' => $foo];
        }
    }
    
  3. Where to Look First:

    • Annotations: Focus on @Inject\Service and @Inject\Parameter annotations.
    • Controller Initialization: Understand that the bundle handles injection during controller initialization (likely via a compiler pass or event subscriber).
    • Symfony Container: Verify the service/parameter exists in the container (e.g., session is a built-in Symfony service, acme_foo should be defined in config.yml).

Implementation Patterns

Usage Patterns

  1. Service Injection: Use @Inject\Service("service_id") to inject any service registered in the container. Example:

    /**
     * @Inject\Service("router")
     */
    private $router;
    
  2. Parameter Injection: Use @Inject\Parameter("parameter_name") to inject container parameters (defined in config.yml or parameters.yml). Example:

    /**
     * @Inject\Parameter("app.title")
     */
    private $appTitle;
    
  3. Type Hints (Optional): While the package doesn’t enforce type hints, adding them improves IDE support and readability:

    /**
     * @Inject\Service("session")
     * @var SessionInterface
     */
    private $session;
    
  4. Bulk Injection: Group related injections (e.g., all services/parameters for a feature) in a single controller or base controller class.

  5. Base Controller: Create a base controller with common injections to avoid repetition:

    abstract class BaseController
    {
        /**
         * @Inject\Service("twig")
         */
        protected $twig;
    
        /**
         * @Inject\Parameter("app.locale")
         */
        protected $locale;
    }
    

Workflows

  1. Development Workflow:

    • Start with a single controller to test injection.
    • Gradually add more injections as needed.
    • Use IDE autocompletion for service/parameter names (e.g., symfony/var-dumper for debugging container contents).
  2. Testing:

    • Mock injected services/parameters in PHPUnit tests using Symfony’s createMock or container overrides.
    • Example:
      $container->set('session', $this->createMock(SessionInterface::class));
      
  3. Integration with Other Bundles:

    • Works seamlessly with Symfony’s dependency injection. No conflicts expected with other bundles using annotations (e.g., SensioFrameworkExtraBundle).
    • For custom bundles, ensure their services/parameters are properly registered in the container.

Integration Tips

  1. Configuration: Define parameters in config.yml or parameters.yml:

    # config.yml
    parameters:
        acme_foo: "bar"
    
  2. Service Overrides: Override services in tests or environments:

    # config_test.yml
    services:
        session:
            class: App\Tests\MockSession
    
  3. Performance: The bundle likely uses a compiler pass to resolve injections at compile time. Avoid overusing it for heavy services (e.g., database connections) in controllers; prefer constructor injection in services instead.

  4. Legacy Code: For controllers without annotations, manually fetch services/parameters via the container:

    $this->get('session')->get($this->container->getParameter('acme_foo'));
    

Gotchas and Tips

Pitfalls

  1. Missing Services/Parameters:

    • Error: ServiceNotFoundException or ParameterNotFoundException if the service/parameter doesn’t exist.
    • Fix: Verify the service/parameter is registered in the container (e.g., php bin/console debug:container).
  2. Annotation Parsing:

    • Error: Injections may not work if annotations are malformed or the bundle isn’t enabled.
    • Fix: Ensure the bundle is listed in AppKernel::registerBundles() and annotations are correctly formatted.
  3. Circular Dependencies:

    • Injecting services with circular dependencies (e.g., ServiceA injects ServiceB, which injects ServiceA) may cause issues.
    • Fix: Refactor to use constructor injection in services or avoid injecting services into controllers.
  4. Late Initialization:

    • Injections happen during controller initialization. Avoid calling methods that rely on injected properties before they’re set (e.g., in __construct).
    • Fix: Initialize properties in the controller’s lifecycle (e.g., initialize() method if using Symfony 2.x).
  5. Namespace Conflicts:

    • The @Inject namespace might conflict with other annotation namespaces.
    • Fix: Use fully qualified annotations:
      /**
       * @Astina\Bundle\InjectionBundle\Annotation\Service("session")
       */
      

Debugging

  1. Check Injections: Dump the container to verify services/parameters exist:

    php bin/console debug:container | grep "service_id\|parameter_name"
    
  2. Compiler Pass Debugging: If injections fail silently, enable debug mode and check logs for AstinaInjectionBundle errors.

  3. Annotation Processing: Use a tool like phpDocumentor to validate annotations:

    composer require --dev phpdocumentor/phpdocumentor
    vendor/bin/phpdoc -d src --parse-tags
    

Tips

  1. IDE Support: Configure your IDE (e.g., PHPStorm) to recognize @Inject annotations for autocompletion and navigation.

  2. Documentation: Document injected services/parameters in the controller’s PHPDoc to clarify dependencies:

    /**
     * @Inject\Service("session")
     * @var SessionInterface $session The Symfony session service.
     */
    
  3. Alternatives:

    • For modern Laravel (or Symfony 4+), prefer constructor injection or autowiring over annotation-based injection.
    • Example (Symfony 4+):
      public function __construct(private SessionInterface $session, private string $foo) {}
      
  4. Extension Points:

    • The bundle is archived, so no official extension points exist. However, you can:
      • Fork and extend the compiler pass to support custom annotations or logic.
      • Override the bundle’s services in config.yml to modify behavior.
  5. Performance Note:

    • Annotations add slight overhead during compilation. For large projects, weigh the convenience of annotations against performance (though this is negligible in most cases).
  6. Testing:

    • Use Symfony’s ContainerAwareInterface or ContainerAwareTrait for testing if injections are problematic:
      $controller = new DefaultController();
      $controller->setContainer($this->createMock(ContainerInterface::class));
      
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
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
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony