Reputation: 490
I need to inject service to controller constructor method
service.yaml
imports:
- { resource: controllers.yaml }
services:
_defaults:
autowire: false
autoconfigure: false
public: false
App\:
resource: '../src/*'
exclude: '../src/{Application/Message,Infrastructure/Repository/MySql/Migrations,Tests,Kernel.php}'
controllers.yaml
app.controller:
class: App\UI\Controller\AppController
arguments:
- '@monolog.logger.api'
tags: ['controller.service_arguments']
app.controller.keyword:
class: App\UI\Controller\BlogController
arguments:
- '@monolog.logger.api'
tags: ['controller.service_arguments']
BlogController.php
class BlogController extends AbstractController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function postForSubscribers(Request $request, FindPostQuery $query): JsonResponse
{
$page = $request->query->get('page') ?? 1;
$limit = $request->query->get('limit') ?? 500;
$daysBack = $request->query->get('days-back') ?? '7';
try {
$results = $query->getResults($daysBack, new Paging((int)$page, (int)$limit));
return new JsonResponse($results->normalize());
} catch (Exception $e) {
$this->logger->warning($e->getMessage(), [
'line' => $e->getLine(),
'file' => $e->getFile(),
'trace' => $e->getTraceAsString(),
]);
return new JsonResponse(['error' => 'Something broken, cant fetch post data.'], 500);
}
}
}
Action postForSubscribers
return The controller for URI "/api/v1/post/subscribers" is not callable. Controller "App\UI\Controller\BlogController" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?
But controllers.yaml contains controller tags, how I should configure my controllers instead? Anyone can help?
PS. When I add to service.yaml:
App\UI\Controller\:
resource: '../src/UI/Controller'
tags: ['controller.service_arguments']
I get: Too few arguments to function App\UI\Controller\BlogController::__construct(), 0 passed in /var/www/html/var/cache/dev/ContainerV9lwkz0/getBlogControllerService.php on line 13 and exactly 1 expected
Upvotes: 2
Views: 7974
Reputation: 568
As I see you didn't exclude your controller from default configuration, add the exclusion here:
exclude: '../src/{Application/Message,Infrastructure/Repository/MySql/Migrations,Tests,Kernel.php}'
Its not necessary but this could override your manual configuration. (It depends which is first).
Then, focus on autowire
parameter, if this parameter is false you have to inject dependency manually using arguments
- see autowiring and service container.
Good luck!
Upvotes: 2