0

I am trying to create a custom service and call it from a controller that is being used on a route. I use simple code, so I think I am missing something

The membership service: https://gist.github.com/betz/6e0cb7ce2712793711d4c9ed99a3a697

Controller: https://gist.github.com/betz/a9aa9db636cd9b9bffea3b4e255fb1df

services file: https://gist.github.com/betz/25aeb579c265bfba83a0e891aa883bf8

routing file: https://gist.github.com/betz/577a411a8ede77ecc0be614044ec1a44

The error I get:

RuntimeException: Controller "Drupal\hsbxl_members\Controller\Test::test()" requires that you provide a value for the "$container" argument (because there is no default value or because there is a non optional argument after this one). in Drupal\Core\Controller\ControllerResolver->doGetArguments() (line 165 of /var/www/drupalvm/web/core/lib/Drupal/Core/Controller/ControllerResolver.php).

So it seems the ContainerInterface $container is missing when the controller is being initiated. But how do i do this? Confused.

Cheers! Tom

marked as duplicate by kiamlaluno Jan 4 '18 at 11:37

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

In this example you should inject dependencies via the controller create method, pass the container there, and return an array. The first item in the array is the service you’re passing to the constructor.

Then, add a constructor that expects this object as an argument, and then set $this->membership to the container object you passed as an argument. This should also be a protected member of the class.

But to see your example actually work first, remove the container from the test method and remove the line about $memebrship. Clear cache and hit that route to see Hello world!

Here is a similar question demonstrating this: How do I use dependency injection on \Drupal::moduleHandler() to a Controller?

  • but what is the difference between create() and __construct()? – betz Oct 15 '17 at 21:05
  • 2
    create passes the arguments to the constructor when the class is instantiated. – Kevin Oct 15 '17 at 21:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.