Search code examples
symfonysymfony4beanstalkd

Symfony 4 autowiring not working properly


Here is the context:

  1. Installed beanstalk bundle with composer "composer require leezy/pheanstalk-bundle"

  2. I'm trying to using inside a command but i get this error

Cannot autowire service "App\Command\Worker\ProcessParserCommand": argument "$pheanstalk" of method "__construct()" references interface "Pheanstalk\Contract\PheanstalkInterface" but no such
service exists. You should maybe alias this interface to the existing "leezy.pheanstalk.proxy.default" service.

class ProcessParserCommand extends Command
{
    protected static $defaultName = 'app:worker:process-parser';

    /** @var PheanstalkInterface $pheanstalk */
    private $pheanstalk;

    protected function configure()
    {
        $this
            ->setDescription("Parse something")
        ;
    }



    public function __construct(PheanstalkInterface $pheanstalk)
    {
        $this->pheanstalk=$pheanstalk;

        parent::__construct();
    }
}

Solution

  • Turns out that this was one of those deceptive error messages.

    Normally when you get an "Interface does not exist, maybe alias SomeService" message it means that the Interface needs to be explicitly defined as an alias:

    # config/services.yaml
    Pheanstalk\Contract\PheanstalkInterface:
        alias: 'leezy.pheanstalk.proxy.default'
    

    But in this case, while doing so gets you past the Interface error, a new "too few constructor arguments" error is produced.

    A peek at the bundle's documentation shows that you need a bit of configuration to actually generate a pheanstalk instance. The composer require command is smart enough to add the bundle to your bundles.php file but does not create a config file. So add the config file per the docs:

    # config/packages/leezy_pheanstalk.yaml
    leezy_pheanstalk:
        pheanstalks:
           primary:
               server: beanstalkd.domain.tld
               default: true
    

    And presto. The error goes away. As a bonus, the alias in config/services.yaml is no longer needed and should be removed if you added it.