Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11601

Symfony Routing component standalone - how to add arguments for a controller?

$
0
0

I'm using symfony components 5.x

My composer.json file looks like this

{"require-dev": {"phpunit/phpunit": "9.6"    },"autoload": {"psr-4": {"App\\": "app/"        }    },"require": {"symfony/dependency-injection": "^5.4","symfony/config": "^5.4","ext-json": "*","ext-pdo": "*","symfony/monolog-bundle": "^3.10","symfony/cache": "^5.4","twig/twig": "3.0","symfony/security-core": "^5.4","symfony/http-foundation": "^5.4","symfony/security-http": "^5.4","symfony/event-dispatcher": "^5.4","symfony/http-kernel": "^5.4","symfony/routing": "^5.4"    }}

I'm trying to use the routing component to define some routes. Currently I only have 1 route defined like this

$routes = new RouteCollection();$routes->add('shop_info',    new Route('/api/v1/shop/info', ['_controller' => [ShopController::class, 'index'],    ]));

The route itself works fine.

The problem arises when trying to instantiate the controller itself.

The index function expects an argument.

class ShopController{    public function index(AgentRepository $agentRepository): JsonResponse    {        return new JsonResponse(['test' => 1234]);    }}

I would also be perfectly happy with constructor arguments(although some may not be used, so I'd prefer method arguments).

class ShopController{    private AgentRepository $agentRepository;    public function __construct(AgentRepository $agentRepository)    {        $this->agentRepository = $agentRepository;    }    public function index(): JsonResponse    {        return new JsonResponse(['test' => 1234]);    }}

AgentRepository itself also has a few arguments of its own.

I'm at a loss how I would instantiate these arguments. I was hoping I could use the DI container but it doesn't seem to do that by default and I can't figure out how to add a custom ArgumentResolver. Even if I did I would still have a n number of cascading arguments to resolve so that doesn't help much.

I tried following this "guide" from the symfony official docs/site https://symfony.com/doc/5.x/create_framework/dependency_injection.html but it doesn't go into much detail on how to use the components besides a very simple introduction.

I'm looking for a more detailed example of how to solve this issue. A link to a article/guide/whatever is also fine.


Viewing all articles
Browse latest Browse all 11601

Trending Articles