phpsymfonyautowired

Ignore a class in a autowired directory


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.


Solution

  • 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.