N
N
nepster-web2016-11-15 18:59:22
symfony
nepster-web, 2016-11-15 18:59:22

How to correctly inject dependencies into a symfony3 controller?

Using the laravel5 example, I binded the implementation to the interface and simply requested the interface I needed in the method or constructor, and the framework itself substituted the necessary class instance for me.
Here I have to describe everything in the yml config and call the dependency via $this->get('app.product.create.handler') or something like in laravel5 get by object type.
But I ran into some problem in the controllers. That is, in the action $this->get('app.product.create.handler')
works, but in the constructor it gives an error Error: Call to a member function get() on null
Although in all other situations everything works, this behavior seems to be only applies to controller constructors, why is this happening?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
shaqster, 2016-11-15
@shaqster

It is enough to look at the implementation of the Controller class and everything will become obvious. The reference to the container instance gets to the controller via the setContainer method, which is used by DI. So you are rightfully getting an error.
In answer to your question: don't inject dependencies into the controller. Pull them into action as needed, or better yet, throw all the business logic into managers, repositories, providers, builders, etc and use action only to render the response.

1
1alexandr, 2016-11-16
@1alexandr

// ...Controller/ProductController.php

class ProductController extends Controller
{
  private $service;

  public function __construct(ServiceInterface $serviceInterface)
  {
    $this->service = $sserviceInterface;
  }
}

// Bundle/.../Service.php

class Service extends ServiceInterface
{
  ...
}

// src/.../Resources/config/service.yml
services:

  ...
  
  controller.product:
    class: Bundle/Controller/ProdcutController
    arguments: ["@service"]

  bundle.service:
    class: Bundle/Service
    arguments: ["@other_service", "@another_service"]

  bundle.another_service:
    class: AnotherService
    argum....
  ...

IMHO accessing services via $this->get('bundle.service') is not a good option...
or use what shaqster suggested

M
Mikhail Osher, 2016-11-15
@miraage

I am using JMSDiExtraBundle . Amazing contraption.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question