Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 745
Oskar Calvo Avatar asked Oct 20 '25 14:10

Oskar Calvo


1 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).

like image 94
lionelto Avatar answered Oct 22 '25 03:10

lionelto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!