Controller
creating a controller
we can create a controller in two way, one is a manual way and second way is using a command prompt. Let's see how symfony offer to create a controller using CLI
php bin/console make:controller ProductController
This command will create a ProductController.php inside src/Controllers directory.
product/list route
Now once controller is created we have to define an action that can handle product/list request when user hits that route. Normally most of the framework uses separate routes file. Symfony also supports that, but in order to make things simple PHP version 8 and above supports class attributes. We can define attributed routes in Symfony controller it self. So there is no need to have a separate route file. Now let's add a simple products/list route
<?php
namespace App\Controller;
use App\Service\AuthHelperService;
use App\Service\ProductService;
use Symfony\Component\HttpFoundation\Response;
final class ConferenceController extends BaseController
{
private ProductService $productService;
public function __construct( AuthHelperService $authHelper,ProductService $productService)
{
parent::__construct($authHelper);
$this->productService = $productService;
}
#[Route('products/list', name: 'product_list', methods: ['GET'])]
public function productList(): Response
{
$products = $this->productService->getProductList();
//$content = $this->template('users/user_list', ['products' => $products$]);
$content = $this->template('users/user_list', compact('products'));
return new Response($content);
}
}
As we can see that we have written #Route just above the controller action method. This is called attributed routes in symfony. Because of this attributed routes we do not have to write explicit routes.yaml or routes.php/xml
Now attributes routes have some parameters inside it. Let’s understand it step by step.
routes
#[Route('products/list', name: 'product_list', methods: ['GET'])]
- This is an attribute-based route declaration (available since Symfony 5.2).
- When a user accesses /products/list with a GET request, this productList() method is executed.
- name: 'product_list' gives this route an identifier, which is useful in templates, redirects, etc.
Dependency Injection (DI)
public function __construct(AuthHelperService $authHelper, ProductService $productService)
- Symfony automatically injects services (like AuthHelperService and ProductService) into the controller.
- This happens via the constructor and is configured in Symfony’s service container (usually via autowiring).
- These services are likely defined as @service-tagged classes in your services.yaml or via attributes.
In this case:
AuthHelperService: Possibly handles authentication, access control, or token validation. Passed to the BaseController.
ProductService: Handles business logic related to products, like retrieving the list of products. Used directly here.