Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony4 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.)
like image 537
okey_on Avatar asked Jun 07 '18 18:06

okey_on


4 Answers

I had the same problem with my first Symfony 4 project on a standard Apache web server.

Creating a .htaccess file in my public folder fixed the issue.

<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        RedirectMatch 302 ^/$ /index.php/
    </IfModule>
</IfModule>
like image 185
Julien B. Avatar answered Sep 23 '22 12:09

Julien B.


Make sure you install the annotations library with composer require annotations.

This was my issue and not other ones described here.

like image 39
Hamlet Avatar answered Sep 24 '22 12:09

Hamlet


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;

like image 24
okey_on Avatar answered Sep 23 '22 12:09

okey_on


I want to give additional advice about annotation errors in Symfony 4:

I handled my issue with that:

My project doesn't have file config/routes/annotation.yaml, so create that file and write these lines:

// config/routes/annotations.yaml

controllers:
    resource: ../../src/Controller/
    type: annotation
like image 23
muhammed celik Avatar answered Sep 21 '22 12:09

muhammed celik