Ivo
Ivo

Reputation: 363

Inject service in FOSRest Controller

I am new at symfony and trying to create REST api using FOSRest Bundle. Also i want to use flysystem library as service in my controllers. It is simple as that

class FileController extends FOSRestController
{
    public function getFilesAction()
    {
        $filesystem = $this->container->get('oneup_flysystem.application_filesystem');
        ...
    }
}

This works fine, but my idea is to Inject this service into FileController so i can use $filesystem service in every method in my controller.

I read about it, that I have to make my controller as service, but then something went wrong. What is the proper way to make this injection.

Upvotes: 0

Views: 322

Answers (1)

honzalilak
honzalilak

Reputation: 376

We use something like this:

YourBundle/Resources/config/services.yml

    controller.file:
    class: YourBundle\Controller\FileController
    arguments:
        - @yourFileService 
        - @service_container

YourBundle/Controller/FileController.php

/**
 * @Route("/file", service="controller.file")
 */
class FileController extends Controller
{

    /**
     * @var Filesystem
     */
    private $filesystem;

    /**
     * @param Filesystem $filesystem
     * @param $container
     */
    public function __construct(
        Filesystem $filesystem,
        $container
    ) {
        $this->filesystem = $filesystem;
        $this->container = $container;
    }

Upvotes: 1

Related Questions