Search code examples
symfonyroutesannotationssymfony4

Symfony 4 annotation routing does not work


I just started learning Symfony. I am following this official tutorial exactly. Routing works fine when done with config/routes.yaml, but on using annotations:

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Annotation\Route;

class LuckyController
{

    /**
     *  @Route("/lucky/number")
     */
    public function number(){

        $number = mt_rand(0, 100);

        return new Response(
            '<html><body><h1>MyLucky Number: ' . $number . '</h1></body></html>'
        );
    }
}

I get this error:

    Exception thrown when handling an exception
(Symfony\Component\Config\Exception\FileLoaderLoadException: [Semantical Error]
 The annotation "@Symfony\Component\Annotation\Route" in method
App\Controller\LuckyController::number() does not exist, or could not be auto-loaded
 in C:\wamp\vhosts\mysymfony4\config/routes\../../src/Controller/ (which is
 being imported from "C:\wamp\vhosts\mysymfony4\config/routes/annotations.yaml"). Make sure
 annotations are installed and enabled.)

Solution

  • I found out my mistake. I used the wrong namespace for routing.

    use Symfony\Component\Annotation\Route;

    It should have been:

    use Symfony\Component\Routing\Annotation\Route;