Home > OS >  Symfony router {_controller} param
Symfony router {_controller} param

Time:03-29

i'm new to Symfony. I'm trying to create dynamic universal route that will pick required controller based on part of url. I've found in docs that there is special param {_controller} that can be used in route pattern, but could not find any examples of usage.

// config/routes.yaml
api:
    path: /api/{_controller}

So for example for route /api/product i expect ProductController to be initiated. But as a result i get error "The controller for URI "/api/product" is not callable: Controller "product" does neither exist as service nor as class."

Can somebody please help me understanding how {_controller] param works? Or maybe there is a better way for specifying universal route that can dynamically chose controller without listing controller names in routes.yaml.

Thanks in advance

CodePudding user response:

This isn't really the cleanest way to do what I think you're trying to do. If I am correct in assuming you want to have a /api/product/ point to methods in your product controller, then something like this is more "symfonyish"

// src/Controller/ProductController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/api/product", name="product_")
 */
class ProductController extends AbstractController
{
    /**
     * @Route("/", name="index")
     * --Resolves to /api/product/
     */
    public function index(): Response
    {
        // ...
    }

    /**
     * @Route("/list", name="list")
     * --Resolves to /api/product/list
     */        
    public function list(): Response
    {
        // ...
    }

    /**
     * @Route("/{productID}", name="get")
     * --Resolves to /api/product/{productID}
     */        
    public function get(string $productID): Response
    {
        // $productID contains the string from the url
        // ...
    }
}

Note that this really just scratches the surface of Symfony routing. You can also specify things like methods={"POST"} on the routing directive; so you could have the same path do different things depending on the type of request (e.g. you could have a route /product/{productID} that GETs the product on that request but updates the product on a PATCH request.

Regardless, the takeaway here is that it is unwieldy to have all of your routes defined in routes.yml rather you should define your routes as directives in the controller itself.

  • Related