phpsymfonyphp-8

php symfony 6.0, routing


php version: 8.0.30 Symfony: 6.0

I’m creating my first project on Symphony, I encountered a problem in the controller, creating all the entities, repositories and the first service together with the controller. Here's the controller itself:

namespace App\Controller;

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

class ProductController extends AbstractController
{

    public function __construct(private ProductService $productService)
    {
    }

    #[Route('/products', name: 'product_list')]
    public function getProducts(): Response
    {
        $products = $this->productService->getAll();
        $status = true;

        if (!$products) {
            $status = false;
        }

        return new Response(json_encode(["success" => $status, "products" => $products]));
    }
}

Also, according to the Symphony documentation, I created an additional file in config/routes/attributes.yaml

controllers:
  resource: ../../src/Controller/
  type: attribute

kernel:
  resource: ../../src/Kernel.php
  type: attribute

when I try to run the command - PHP bin/console debug:router

gives this error:

Cannot load resource "../../src/Controller/". Make sure there is a loader supporting the "attribute" type.

I found a solution in Google, upgrade to Symphony 6.2 or higher, but I have an old IDE, I don’t want to download the new version, the Symphony 6.0 documentation says that you can do the same on this version. I should also note that this is a symphony API, without templates. Front on Next.js.


Solution

  • Upgrading to Symfony 6.2 remains the best option.

    Whatever, if you won't/can't, to fix this, replace your attributes.yaml file by annotations.yaml, then update its content like this:

    controllers:
      resource: ../../src/Controller/
      type: annotation
    
    kernel:
      resource: ../../src/Kernel.php
      type: annotation
    

    You could still define your route like:

    class ProductController extends AbstractController
    {
        #...
        
        #[Route('/products', name: 'product_list')]
        public function getProducts(): Response