9

I have an Exception somewhere in my service/ folder, and Symfony is trying to autowire it :

Cannot autowire service "App\Service\Order\Exception\StripeRequiresActionException": argument "$secretKey" of method "__construct()" is type-hinted "string", you should configure its value explicitly.

This is my class :

class StripeRequiresActionException extends \Exception
{
    /**
     * @var string
     */
    protected $secretKey;

    public function __construct(string $secretKey)
    {
        parent::__construct();

        $this->secretKey = $secretKey;
    }

    /**
     * @return string
     */
    public function getSecretKey(): string
    {
        return $this->secretKey;
    }
}

I don't want it to be autowired. Is there an easy way to prevent this class to be loaded by the DI, with an annotation for example? I know I can exclude this class in my yaml configuration, but I don't want to do that because I find this ugly and harder to maintain.

4 Answers 4

15

Maybe you could exclude all exceptions, no matter where they are.

If all your exceptions follow the pattern you show in your question, you could do something similar to:

App\:
  resource: '../src/*'
  exclude: ['../src/{Infrastructure/Symfony,Domain,Tests}', '../src/**/*Exception.php']

This comes directly from a project I have open right here. The default exclude for Symfony looks somewhat different. But the important bit would be to add the pattern *Exception.php to the excluded files.

This is simpler to maintain than an annotation, even if an annotation were possible (which I believe it's not). Keeps the configuration all in a same place, you can create new exceptions without having to change configuration or add unnecessary code.

1
  • 2
    You are right, this is smarter like that than with an annotation. It works well, I just had to do ../src/Service/**/{*Exception.php} to make it work in all subfolders. Thank you. Sep 9, 2019 at 13:56
7

Even if I agree that in your particular case the cleanest way is to do what yivi suggested, I think I have a more generic solution that could suit more cases.

In my case I have a PagesScanner service that returns PageResult objects, both are several level deep into an autowired directory.

Excluding the class like suggested is a pain and will make the yaml unreadable quickly as the number of exceptions increases.

So I created a new compiler pass that searches for an @IgnoreAutowire annotation on each class under the App/ folder :

<?php
namespace App\DependencyInjection\Compiler;

use App\Annotation\IgnoreAutowire;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

final class RemoveUnwantedAutoWiredServicesPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $annotationReader = new AnnotationReader();
        $definitions = $container->getDefinitions();
        foreach ($definitions as $fqcn => $definition) {
            if (substr($fqcn, 0, 4) === 'App\\') {
                try {
                    $refl = new \ReflectionClass($fqcn);
                    $result = $annotationReader->getClassAnnotation($refl, IgnoreAutowire::class);
                    if ($result !== null) {
                        $container->removeDefinition($fqcn);
                    }
                } catch (\Exception $e) { 
                    // Ignore
                }
            }
        }
    }
}

This way all I have to do is to add the annotation to classes I don't want to be autowired:

<?php
namespace App\Utils\Cms\PagesFinder;

use App\Annotation\IgnoreAutowire;

/**
 * @IgnoreAutowire()
 */
class PageResult
{
    [...]
}

Another good thing about this approch is you can even have parameters in the class constructor without any error because the actual autowiring thing is done after the compiler pass.

4

BTW code for php8 attributes:

CompilerPass

<?php
namespace App\DependencyInjection\Compiler;

use App\Annotation\IgnoreAutowire;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

final class RemoveUnwantedAutoWiredServicesPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $definitions = $container->getDefinitions();
        foreach ($definitions as $fqcn => $definition) {
            if (str_starts_with($fqcn, 'App\\')) {
                try {
                    $refl = new \ReflectionClass($fqcn);
                    $attribute = $refl->getAttributes(IgnoreAutowire::class)[0] ?? null;
                    if ($attribute !== null) {
                        $container->removeDefinition($fqcn);
                    }
                } catch (\Exception $e) {
                    // Ignore
                }
            }
        }
    }
}

Attribute

<?php

namespace App\Annotation;

use Attribute;

/**
 * Annotation class for @IgnoreAutowire().
 *
 * @Annotation
 * @Target({"CLASS"})
 */
#[Attribute(Attribute::TARGET_CLASS)]
class IgnoreAutowire
{
}
1
  • Obviously going with native attributes is ideal in a post PHP 7 world. Further, the idea of adding exclusions to some jumbled mess of config files is only desirable if you have some really defined pattern for exclusion. In our case, and I would assume many others, this is far less ideal to adding a contextual attribute on the class itself. Exceptions are just one example. There are generally numerous value objects that accompany services - as there should be. In addition to that, there are many "services" that, frankly, don't need to be part of the service container at all. Jul 30 at 3:36
2

You can also disable autoconfigure for only this class in config/services.yaml:

App\Service\Order\Exception\StripeRequiresActionException:
    autoconfigure: false

Symfony won't add this class to the DI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.