How can I load a vendor class as a Service in Symfony 4?

Viewed 3348

I'm using the jwt firebase class in a project, it's path in vendor is:

vendor\firebase\php-jwt\src\jwt

I'm trying to define the class as a service to be able to inject in another class, but I'm not able to do it.

I'm to do this in the service.yml file:

#services.yaml    
services:
    Firebase:
        class: '../vendor\firebase\php-jwt\JWT'

An this is the class I have created:

<?php

namespace App\Helpers;

use Firebase\JWT\JWT;

use Symfony\Component\HttpKernel\KernelInterface;

class simpleJwt
{
    private $encrypt = 'RS256';

    function __construct(KernelInterface $kernel, JWT $JWT )
    {
        $this->rootDir = $kernel->getProjectDir();
        $this->jwt = $JWT;
    }
}

When I try to load it I get this error:

Cannot autowire service "App\Helpers\simpleJwt": argument "$JWT" of method "__construct()" references class "Firebase\JWT\JWT" but no such service exists. 

Thanks

3 Answers

Just add full namespace in config.yaml

services:

    Firebase\JWT\JWT:

You can also provide to your service constructor requirements, using arguments:

services:

    Namespace\Domain\ServiceName:
        arguments:
            - '@Another\Namespace\Class'
            - '@service.name'
            - '%parameter%'

More details and features in the official documentation : Service Container (Symfony Docs)

Note you'll access your service through AutoWiring and that you won't access to it directly through the container, cause service public argument is set to false by default (public: true is not recommended according to Symfony documentation).

Try adding ‘autowire: true’ in your services.yaml, right under ‘class: ../vendor\firebase\php-jwt\JWT’

It could be that the bundle you are trying to import might not be compatible with Symfony’s autowire. Be sure to use the latest version of the bundle (newer versions might be compatible). In case you’re already using the lastest version, you might need to create an alias for that bundle in your services.yaml so you can use it later on your classes. You can use bin/console debug:container to check what services are available and manually create an alias for the service you need. It happens that autowire is commonly turned off in most of the vendor bundles.

Related