Symfony2 won't pass arguments to a service - php

I am trying to pass arguments to my new Controller in new Bundle I have created via cli ( I have tried to do it manually too ). It can be anything, string, service, parameter from parameters.yml file, nothing comes through.
Error:
{"code":500,"message":"Warning: Missing argument 1 for MyProject\\PosBundle\\Controller\\OfferController::__construct(), called in \/var\/www\/vhosts\/httpdocs\/myproject\/vendor\/symfony\/symfony\/src\/Symfony\/Component\/HttpKernel\/Controller\/ControllerResolver.php on line 162 and defined","errors":null}
My Files are
service.yml
services:
myproject_pos_offer_controller:
class: MyProject\PosBundle\Controller\OfferController
arguments: ['templating']
I have tried to do this:
services:
myproject_pos_offer_controller:
class: MyProject\PosBundle\Controller\OfferController
arguments:
someString: 'templating'
OfferController:
class OfferController extends RestController
{
private $someString;
public function __construct($someString)
{
$this->$someString = $someString;
}
public function indexAction(){
}
}
What am I doing wrong or what did I forget to do?

And Cerad was right (Thanks for help!). I had to pass my controller in my routing.yml configuration as a service. Do find that I had to debug ControllerResolver.php, that was fun.
Solution
Code above is correct. The problem was lying in my routing.yml
Wrong
myproject_pos.offer_create:
path: /{store_hash}/offers
defaults: { _controller: MyProjectPosBundle:Offer:create }
methods: 'POST'
Correct
myproject_pos.offer_create:
path: /{store_hash}/offers
defaults: { _controller: myproject_pos_offer_controller:createAction }
methods: 'POST'
As you see the key is in defaults attrubute.

Related

Controller has no container set, did you forget to define it as a service subscriber? Symfony 5

I'm making my first application on Symfony 5
I ran into a problem when creating a controller, and I need a controller, not a service
Uncaught PHP Exception LogicException: ""App\Controller\UploadFileController" has no container set, did you forget to define it as a service subscriber?" at /vendor/symfony/framework-bundle/Controller/ControllerResolver.php line 36
it is my simple Controller
class UploadFileController extends AbstractController
{
/**
* #Route("/test-upload", name="app_test_upload")
*/
public function testAction(Request $request, FileUploader $fileUploader)
{
return 1;
}
}
I tried to clean the cache, it didn't help
this is my services.yaml
services:
App\Controller\UploadFileController:
calls:
- [setContainer, ['#service_container']]
There is no need to add any releated information in your service.yaml file, you only need to edit your code in service.yaml file to be like that:
App\Controller\:
resource: '../src/Controller/'
tags: ['controller.service_arguments']

Symfony 3.4 - Auto wire of service not working in method

I'm relatively new to Symfony, and I'm having trouble some trouble.
I'm trying to type hint a custom RequestValidator class in the method being called when the endpoint is called.
Using Symfony 3.4
However, I am getting the following error:
Controller "ApiBundle\Endpoints\Healthcheck\v1\Index::check()" requires that you provide a value for the "$request" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
Here is my setup:
services.yml file
...
_defaults:
autowire: true
autoconfigure: true
...
routing.yml
api.Healthcheck:
path: /healthcheck
controller: ApiBundle\Endpoints\Healthcheck\v1\Index::check
defaults: { _format: json }
methods:
- GET
And then - inside the Index class, I have the following:
<?php
namespace ApiBundle\Endpoints\Healthcheck\v1;
use ApiBundle\Responses\ApiResponse;
class Index extends ApiResponse
{
public function check(HealthcheckRequest $request) {
var_dump($request);die;
}
}
When I do debug:autowiring I see my HealthcheckRequest in the list.
Further, when I do the same and try type-hint in the constructor of the Index class, it all works.
And finally, if I try and type hint the Symfony/HttpFoundation/Request, inside the check() method, it instantiates it correctly.
In summary:
Not working :
check(HealthcheckRequest $request)
Working:
__construct(HealtcheckRequest $request)
check(SymfonyRequest $request)
Am I doing something wrong? Any help is appreciated.
It's part of services.yaml already in Symfony 4, but introduced in version 3.3, so this might help:
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
ApiBundle\Endpoints\:
resource: '../../Endpoints/*'
tags: ['controller.service_arguments']

How to pass variable to controller without routing?

class HelloController
{
/**
* #Route("/", name="hello")
*/
public function indexAction($name)
{
return new Response($name);
}
}
I would like pass variable $name to indexAction without use routing.
In documentation I found:
services:
# ...
# explicitly configure the service
AppBundle\Controller\HelloController:
public: true
tags:
# add multiple tags to control
- name: controller.service_arguments
action: indexAction
argument: logger
# pass this specific service id
id: monolog.logger.doctrine
This shows us how to pass another service to the controller, but how to pass a simple variable?
try this inside routing.yml:
defaults:
_controller: AppBundle:Hello:index
name: "WhatYouWantToPass"

Argument 1 passed to __construct must be an instance of Services\ProductManager, none given

in service.yml
test_product.controller:
class: MyBundle\Controller\Test\ProductController
arguments: ["#product_manager.service"]
in controller
class ProductController extends Controller
{
/**
* #var ProductManager
*/
private $productManager;
public function __construct(ProductManager $productManager){
$this->productManager = $productManager;
}
}
in routing.yml
test_product_addNew:
path: /test/product/addNew
defaults: { _controller:test_product.controller:addNewAction }
I want to use ProductManger in contructor to do some stuff but it gives me this error
Catchable Fatal Error: Argument 1 passed to
MyBundle\Controller\Test\ProductController::__construct()
must be an instance of MyBundle\Services\ProductManager,
instance of Symfony\Bundle\TwigBundle\Debug\TimedTwigEngine given,
called in
..../app/cache/dev/appDevDebugProjectContainer.php
on line 1202 and defined
I am new to symfony, any help is appreciated
You have inverted the logical of services.
First, it's your manager wich must be defined as a service because it's it you will need to call from controller.
// services.yml
product_manager:
class: MyBundle\Path\To\ProductManager
Then call directly your manager defined as a service in your controller.
// Controller
class ProductController extends Controller
{
[...]
$this->get('product_manager');
[...]
}
And you do not need to overload __construct() methode. Only call ->get(any_service) where you need it.
Also your route is wrong. You have to define controller from is namespace.
// routing.yml
test_product_addNew:
path: /test/product/addNew
defaults: { _controller:MyBundle:Product:addNew }
Since Symfony 3.3 (released May 2017) you can use contructor injection and autowiring with ease:
# services.yml
services
_defaults:
autowire: true
MyBundle\Controller\Test\ProductController: ~
Keep rest as you already had.
Do you want to know more about there features? Check this post with examples.

Symfony 2 InvalidArgumentException when creating a new service

I'm trying to create my first service in a symfony 2 application and I get this error :
InvalidArgumentException: There is no extension able to load the
configuration for "my_app.myservice" (in
/path/to/src/MyApp/MyBundle/DependencyInjection/../Resources/config/services.yml).
Looked for namespace "my_app.myservice", found none.
It seems there's a problem in my configuration but I don't see what it is.
Here's my services.yml
services:
my_app.myservice:
class: MyApp\MyBundle\Service\MyService
And my service looks like this
<?php
namespace MyApp\MyBundle\Service;
class MyService
{
public function run()
{
echo "hello world";
}
}
Thanks for help !
Just to be sure - do you have proper indentation in the services.yml?
It should be:
services:
my_app.myservice:
class: MyApp\MyBundle\Service\MyService
not:
services:
my_app.myservice:
class: MyApp\MyBundle\Service\MyService
Do you have any argument in your service's constructor ?
For example i pass the logger in all my services.
it's result that i have to pass it in my service.yml
service.yml
services:
blog:
class:Site\Backend\BlogBundle\Service\BlogService
arguments: [#logger]
tags:
- { name: monolog.logger, channel: blog}
BlogService
public function __construct(LoggerInterface $logger){
$this->logger = $logger;
}

Categories