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.)
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>
Make sure you install the annotations
library with composer require annotations
.
This was my issue and not other ones described here.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With