Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Rutas, Controladores & Respuestas!

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

La página que estamos viendo ahora... la cual es súper divertida... e incluso cambia de color... está aquí solo para decir "Hola!". Symfony muestra está página porque, en realidad, nuestra aplicación aun no tiene ninguna página. Cambiemos eso.

Ruta + Controlador = Página

Cada framework web... en cualquier lenguaje... tiene la misma labor principal: brindarte un sistema de ruteo -> controlador: un sistema de dos pasos para construir páginas. La ruta define la URL de la página y en él controlador es donde escribimos código PHP para construir esa página, como HTML ó JSON.

Abre config/routes.yaml:

#index:
# path: /
# controller: App\Controller\DefaultController::index

Mira! ya tenemos un ejemplo! Descomentarízalo. Si no te es familiar el formato YAML, es súper amigable: es un formato de configuración tipo llave-valor que se separa mediante dos puntos. La identación también es importante.

Esto crea una simple ruta donde la URL es /. El controlador apunta a una función que va a construir esta página... en realidad, esto apunta a un método de una clase. En general, esta ruta dice:

cuando el usuario vaya a la homepage, por favor ejecuta el método index de la clase DefaultController.

Ah, y puedes ignorar esa llave index que está al principio del archivo: es solo el nombre interno de la ruta... y aun no es importante.

Nuestra Aplicación

El proyecto que estamos construyendo se llama "Cauldron Overflow". Originalmente queríamos crear un sitio donde los desarrolladores puedan hacer preguntas y otros desarrolladores pudieran responderlas pero... alguien ya nos ganó... hace como... unos 10 años. Así como cualquier otro impresionante startup, estamos pivoteando! Hemos notado que muchos magos accidentalmente se han hecho explotar... o invocan dragones que exhalan fuego cuando en realidad querían crear una pequeña fogata para azar malvaviscos. Así que... Cauldron Overflow está aquí para convertirse en el lugar donde magos y hechiceros pueden preguntar y responder sobre desventuras mágicas.

Creando un Controlador

En la homepage, eventualmente vamos a listar algunas de las preguntas más recientes. Así que vamos a cambiar la clase del controlador a QuestionController y el método a homepage.

index:
path: /
controller: App\Controller\QuestionController::homepage

Ok, la ruta está lista: define la URL y apunta al controlador que va a construir la página. Ahora... necesitamos crear ese controlador! Dentro del directorio src/ ya existe el directorio Controller/ pero está vacío. Haré click derecho aquí y seleccionaré "Nueva clase PHP". Llamalo QuestionController.

Namespaces y el Directorio src/

Ooh, mira esto. El namespace ya está ahí! Sorprendente! Esto es gracias a la configuración de Composer en el PhpStorm que agregamos en el último capítulo.

Así está la cosa: cada clase que creamos dentro del directorio src/ va a requerir un namespace. Y... por alguna razón que no es muy importante, el namespace debe iniciar con App\ y continuar con el nombre del directorio donde vive el archivo. Como estamos creando este archivo dentro del directorio Controller/, su namespace debe ser App\Controller. PhpStorm va a autocompletar esto siempre.

... lines 1 - 2
namespace App\Controller;
... lines 4 - 6
class QuestionController
{
... lines 9 - 12
}

Perfecto! Ahora, porque en routes.yaml decidimos nombrar al método homepage, crealo aquí: public function homepage().

... lines 1 - 2
namespace App\Controller;
... lines 4 - 6
class QuestionController
{
public function homepage()
{
... line 11
}
}

Los Controladores Deben Regresar Una Respuesta

Y... felicitaciones! Estás dentro de una función del controlador, el cual algunas veces es llamado "acción"... solo para confundirnos. Nuestro trabajo aquí es simple: construir esa página. Podemos escribir cualquier código para hacerlo - como ejecutar queries en la base de datos, cachear cosas, realizar llamados a APIs, minar criptomonedas... lo que sea. La única regla es que la función del controlador debe regresar un objeto del tipo Symfony Response.

Escribe return new Response(). PhpStorm intenta autocompletar esto... pero existen multiples clases Response en nuestra app. La que queremos es la Symfony\Component\HttpFoundation. HttpFoundation es una de las partes - o "componentes" - más importantes en Symfony. Presiona tab para autocompletarlo.

Pero detente! Viste eso? Como dejamos que PhpStorm autocompletara esa clase por nosotros, escribió Response, pero también agregó la declaración de esa clase al principio del archivo! Esa es una de las mejores funciones de PhpStorm y lo utilizaré bastante. Me verás constantemente escribir una clase y dejar que PhpStorm la autocomplete. Para que agregue la declaración en el archivo por mi.

Dentro de new Response(), agrega algo de texto:

Pero qué controlador tan embrujado hemos conjurado!

... lines 1 - 2
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class QuestionController
{
public function homepage()
{
return new Response('What a bewitching controller we have conjured!');
}
}

Y... listo! Acabamos de crear nuestra primera página! Vamos a probarla! Cuando vamos a la homepage, debería ejecutar nuestra función del controlador... la cual regresa el mensaje.

Encuentra tu navegador. Ya estamos en la homepage... así que solo refresca. Saluda a nuestra primerísima página. Lo sé, no hay mucho que ver aun, pero acabamos de cubrir la parte más fundamental de Symfony: el sistema ruta-controlador.

A continuación, hagamos nuestra ruta más elegante al usar algo llamado anotaciones. También vamos a crear una segunda página con una ruta que utiliza comodines.

Leave a comment!

83
Login or Register to join the conversation
Mohsen-A Avatar
Mohsen-A Avatar Mohsen-A | posted hace 7 días

in my route.ymal I don't know where i put my method :

controllers:
    resource: ../src/Controller/QuestionController
    type: annotation

kernel:
    resource: ../src/Kernel.php
    type: annotation
Reply

Hey Mohsem,

I'm not sure I understand your question... Usually you don't need to specify methods there, the first few lines should register all your classes in the resource: ../src/Controller/ dir, i.e. this way you should not write a specific controller there, only the dir to all your controllers, i.e.:

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

And it will register all your controllers, i.e. it will read all your route configuration there.

if you want to specify exact controller - you should use the code from the tutorial: https://symfonycasts.com/screencast/symfony5/route-controller#codeblock-b54cc0bccb where you need to specify the exact method. But then you should remove those few lines that are responsible for registering all your controllers or change it to avoid conflicts.

Cheers!

Reply
Marius S. Avatar
Marius S. Avatar Marius S. | posted hace 1 año

Hi together,
I'm trying do do this cource with my actual configuration. I've installed Symfony CLI version 5.4.1, symfony welcome page at the end of chapter 2 says: Welcome to Symfony 6.0.5.
Because Harmonious Development with Symfony 6 is not available I use this course and now I face the following problem:
The routes.yaml file in my project is totally different from the file in the video:
routes.yaml (video):
# index
# path: /
# controller: App\controller\DefaultController::index

routes.yaml (my project):
controllers:
resource: ../src/Controller/
type: annotation

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

How can I proceed?

Thanks in advance!

Reply

Hey Marius S.

I'd recommend you to wait the next version of tutorial, but the best way for you is to download code from this tutorial and use it instead of one generated by symfony new command. Also as way may be installing symfony 5 instead of 6 you can do it with
symfony new <project_name> --version=5.0

Cheers

Reply
Default user avatar
Default user avatar Brady Cargle | posted hace 1 año

Hey everyone, how's it going?

I'm trying to follow along with this video but the localhost:8000 isn't updating.

I'm running symfony:serve, have the exact code from the video (I copied and pasted just to make sure).

In the console I am seeing this message: [Web Server ] [17-Dec-2021 01:52:29 UTC] [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "No route found for "GET https://localhost:8000/"" at C:\Users\cargl\cauldron_overflow\vendor\symfony\http-kernel\EventListener\RouterListener.php line 135

No other error messages. How can I fix this?

Thanks in advance!

Reply

Hey Brady Cargle

Try to clear cache, better to remove it manually, delete everything inside var/cache/ folder and restart your server, and try again.

Cheers!

1 Reply
Default user avatar
Default user avatar Brady Cargle | sadikoff | posted hace 1 año

That did the job. Thanks Vladimir :)

Reply
Evgeny T. Avatar
Evgeny T. Avatar Evgeny T. | posted hace 1 año | edited

Hey guys, I come from the old layered architecture and trying to get a taste of Symfony.
What is the best approach to rendering different blocks (menu, products, news etc.) on the same page?
I googled and apparently you can render multiple controllers inside one Twig view like so:
`{{ render(controller(

    'App\\Controller\\MenuController::index'
)) }}

{{ render(controller(

    'App\\Controller\\NewsController::index'
)) }}`

Is this the proper way to go?
Thanks.

Reply

Hey Evgeny T.

It depends on use-case and your site structure, but it's totally good approach if you have dynamic data which should be included in multiple places.

Cheers!

Reply
Evgeny T. Avatar

Thanks a lot. I just wanted to know if this is a general practice.

Reply
Andreas G. Avatar
Andreas G. Avatar Andreas G. | posted hace 1 año

Hi guys, I always get the message App\Controller\QuestionController" has no container set, did you forget to define it as a service subscriber?

Do you have an idea where the failure could be?
Thanks

Reply

Hi @Andreas

Can you please share your controller code? It's pretty hard to say something without seeing real code =)

Cheers

Reply
Jakub Avatar
Jakub Avatar Jakub | posted hace 2 años | edited

Hi, it says that homepage is unused. I checked it several times. Everything is like on the video. Any idea what's wrong?
`
index:

path: /
controller: App\Controller\QuestionController::homepage

<?php


namespace App\Controller;


use Symfony\Component\HttpFoundation\Response;

class QuestionController
{
public function homepage(){
    return new Response('What a nice site. START WORKING');
    }
}
`
Reply
Jakub Avatar
Jakub Avatar Jakub | Jakub | posted hace 2 años | edited

Idk why it looks for me that only 1st code is posted, so here is 2nd file
`
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class QuestionController
{
public function homepage(){

return new Response('What a nice site. START WORKING');
}

}`

Reply

Hey Jakub

You can ignore that warning. It's just PHPStorm doesn't know that the homepage function is going to be called dynamically by Symfony. Perhaps if you install the Symfony plugin it may help to get the warning away

Cheers!

Reply
Jakub Avatar

I have Symfony plugin. I checked it on site. It doesnt work. I have still Symfony homepage instead of my words

Reply

Oh, I just noticed that you forgot to add the Route annotations on top of your homepage() method. Give it a try

Reply
Chamal P. Avatar
Chamal P. Avatar Chamal P. | posted hace 2 años | edited

Hi,

I have a controller method, that takes ID value and then fetch the user from the database for that ID value. I'm facing the problem that I can not use that controller method in the twig template as the forms action method. It gives me an error when the application loads the page. It says it expect an ID value on the forms action method.
At the moment I am using two controller methods, one method to load the edit page, with the ID value as a parameter and the second method to process the values when form is submitted (and also to use as the forms action method).

The above solution creates lots of problem, such like when it comes to error handling.
My thinking is, there should be a better way to do this, but I can't think of any. I hope any of you will be able to help me out on finding a better solution for this.

Below is my controller codes

below is used to fetch the user from the database and display on the edit page.
`
/**

  • @Route ("/admin/account/edit/{ID}", name="admin_account_edit")
  • @param $ID
  • @param Request $request
  • @param string $uploadDirectory
  • @param FileUploader $fileUploader
  • @return Response
    */

public function editAccount($ID, Request $request, string $uploadDirectory, FileUploader $fileUploader): Response
{

$account = $adminAccountModel->getUserAccountByEmail($ID);
//if there is an account
if ($account != null)
{
    return $this->render("admin/account/edit.html.twig", [
        'account' => $account
    ]);
}
else
{
    //else, return to account listing page
    return $this->redirectToRoute('admin_account');
}

}
`

Below is the post method that process the form submission values. The functionality is incomplete at the moment
`
/**

  • @Route ("/admin/account/edit", name="admin_account_edit_post")
    *
  • @param Request $request
  • @param string $uploadDirectory
  • @param FileUploader $fileUploader
  • @return Response
    */
    public function postEditAccount(Request $request, string $uploadDirectory, FileUploader $fileUploader): Response
    {
    $errors = array();
    $firstName = $request->request->get(Account::COLUMN_NAME_FIRST_NAME);
    $lastName = $request->request->get(Account::COLUMN_NAME_LAST_NAME);
    emailAddress = $request->request->get(Account::COLUMN_NAME_EMAIL);
    $role = $request->request->get(Account::COLUMN_NAME_USER_ROLE);
    $status = $request->request->get(Account::COLUMN_NAME_USER_STATUS);
    $profileImage = $request->files->get(Account::COLUMN_NAME_PROFILE_IMAGE_URL);
    $adminAccModel = AdminAccountModel::createAdminAccountModel($firstName, $lastName, $emailAddress, $role, $status, $profileImage);
if ($request->isMethod("POST"))
{
    //validate values
    $errors = $adminAccModel->validateAdminAccountData(true);
    if ( count($errors) > 0 )
    {
        //show the errors on the page
    }
    else
    {
        //save the data
    }
}

}

`

Below is the twig code for the form submission
`

<form method="POST" action="{{ path('/admin/account/edit') }}" class="row g-3" enctype="multipart/form-data">

//input fields to capture the form values

//and submit button
</form>

`

Appreciate your help on this.

Reply

Hey Chamal P.

You can just remove action="{{ path('/admin/account/edit') }}" attribute from <form> tag and it will send all data to the same page where you are currrently =)

Cheers!

Reply
Default user avatar
Default user avatar sam meunier | posted hace 2 años

hey everyone
i got this error :

The controller for URI
"/" is not callable: Controller "App\Controller\QuestionController" does
neither exist as service nor as class.

i have uncomment all the lines in routes.yaml
what can i do ?

Reply

Hey sam meunier

It looks like Symfony can't find your controller. Can you double-check the namespace of it, and double-check your config/services.yaml file, it should be registering your controllers as services

Cheers!

Reply
Default user avatar
Default user avatar sam meunier | MolloKhan | posted hace 2 años | edited

i have copy the files in script so i'm sure of it.

but i d'ont see the controller in config/services.yaml

it's here :

`# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters:

services:

# default configuration for services in *this* file
_defaults:
    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
    resource: '../src/'
    exclude:
        - '../src/DependencyInjection/'
        - '../src/Entity/'
        - '../src/Kernel.php'
        - '../src/Tests/'
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones

`

thanks

Reply

Seems like you missed some how this piece of config:


services:
    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller/'
        tags: ['controller.service_arguments']
Reply
Default user avatar
Default user avatar sam meunier | MolloKhan | posted hace 2 años | edited

i have copied it seems to work but he say this :

`Invalid "exclude"

pattern when importing classes for "App\Controller\": make sure your

"exclude" pattern (../src/Tests/) is a subset of the "resource" pattern

(../src/Controller/) in

/home/sam/cauldron_overflow/src/../config/services.yaml (which is being

imported from "/home/sam/cauldron_overflow/src/Kernel.php").
`

the src\Tests\ line must go above the App\Controller line or not ?

` # makes classes in src/ available to be used as services

# this creates a service per class whose id is the fully-qualified class name

<-

App\Controller\:
    resource: '../src/Controller/'
    tags: ['controller.service_arguments']
    exclude:
        - '../src/DependencyInjection/'
        - '../src/Entity/'
        - '../src/Kernel.php'
        - '../src/Tests/'  <-
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones

`

sorry i'm new to symfony

Reply

Hey,

Somehow you ended up mixing the configuration. This is how your services.yaml file should look like:


# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

give it a try and let me know if it worked. Oh, and welcome to Symfony! :)

Reply
Default user avatar
Default user avatar sam meunier | MolloKhan | posted hace 2 años | edited

hey,

thank you
it write again :

The controller for URI
"/" is not callable: Controller "App\Controller\QuestionController" does
neither exist as service nor as class.

i think it's the install of Symfony that failed, could it be ?
i had difficult to use the composer and Symfony during the install.

git status :

<blockquote>On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)

    modified:   config/routes.yaml
    modified:   config/services.yaml

Untracked files:
(use "git add <file>..." to include in what will be committed)

    config/services.yaml~
    src/Controller/QuestionController

no changes added to commit (use "git add" and/or "git commit -a")
</blockquote>

composer.json :

{
    "type": "project",
    "license": "proprietary",
    "minimum-stability": "stable",
    "prefer-stable": true,
    "require": {
        "php": ">=7.2.5",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "symfony/console": "5.3.*",
        "symfony/dotenv": "5.3.*",
        "symfony/flex": "^1.3.1",
        "symfony/framework-bundle": "5.3.*",
        "symfony/runtime": "5.3.*",
        "symfony/yaml": "5.3.*"
    },
    "require-dev": {
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php72": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "5.3.*"
        }
    }
Reply

It could be, I'd re-install the vendors directory, and double-check the file name and namespace of the QuestionController

Reply
Default user avatar

i have done :
- rm -rf vendor/*
- composer clearcache : he say : Composer is operating significantly slower than normal because you do not have the PHP curl extension enabled
- composer update

the vendor directory was empty with the rm command and normal with the update command
he says again :

The controller for URI
"/" is not callable: Controller "App\Controller\QuestionController" does
neither exist as service nor as class.

maybe i should get a copy from someone cauldron_overflow map so i can see the difference with mine ?

Reply

The composer warning it's interesting. You should install PHP curl and try again. Another thing you could try is to download again the course project from this page

Reply
Default user avatar

i have rename QuestionController with QuestionController.php and it's work but phpstorm says 2 problems :
- missing function's return type declaration :9
- unused element: 'homepage' 9

Reply

Hey sam meunier

Sorry for my late reply. I got bugged down by the SymfonyWorld conference. You can add the return type to your controller's actions if you want
and about the unused element. You can ignore that warning because PHPStorm does not know that that method it's going to be calle dynamically

Cheers!

Reply
Leonel D. Avatar
Leonel D. Avatar Leonel D. | posted hace 2 años

Hi everyone,

i have a problem i followed the complete video but when i actualise the page "An exception occurred in driver: could not find driver" appear. i dont know what to do.

Reply
Martin Avatar
Martin Avatar Martin | Leonel D. | posted hace 2 años | edited

Hey Leo,

this is probably too late, but I had the same error. What helped was changing the ".env" file (right below vendor). In there, choose the database you are using and fill it with the data needed. For my personal setup, I just use MySQL, uncomment that and comment the "postgresql"-line. Then fill it with data, for me it looked like this:

<br />###> doctrine/doctrine-bundle ###<br /># Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url<br /># IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml<br />#<br /># DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"<br />DATABASE_URL="mysql://root:@127.0.0.1:3306/library_project?serverVersion=5.7"<br /># DATABASE_URL="postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=13&charset=utf8"<br />###< doctrine/doctrine-bundle ###<br />

I hope this helps.

Happy Coding

Martin

1 Reply
Default user avatar

Hi,

I had the same error so i tried Martin's solution, and then the error transformed into "An exception occurred in driver: SQLSTATE[HY000] [2002] connection refused by the computer".

So, i went into "vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOConnection.php", and around line 36 on the __construct(), i changed the $password from null to 'root'.

Then restart your server, and dont forget to start your wamp, xamp or mamp, because in my case it wont work without it (idk if they told us to activate it).

And thanks to Martin !

Reply

Hey Vandilour

Thanks for sharing your solution. All of it depends on how you configured your database in your local machine, so someone will or will not have the same problems as you

Cheers!

Reply

Hey Leo,

It's difficult to say what's wrong from the error message you share with us. What driver exactly? Is it PDO driver to connect to MySQL database? In what file do you see that error? Could you give us a bit more context on this error please? Sharing stacktrace would help.

Cheers!

Reply
Angelika R. Avatar
Angelika R. Avatar Angelika R. | posted hace 2 años

I like the quiz feature very much, but I think that the text of the full answer is misleading. There it is written: "The only rule of a Symfony controller is that it must return a Symfony Response object". Controller is a class and classes do not return objects to my understanding. I think you meant a controller function or an "action" if that's the name. In two places of this text it is the "controller" that returns an object.

Reply

Hi Angelika R.!

I'm really happy you like the quiz feature :)

> but I think that the text of the full answer is misleading

Hmm, I think you're right! As you correctly said, that word controller can mean either the class or the method/function. In this case, we were a bit lazy with our words and could have been more clear. I'm going to update that now!

Thanks!

Reply
Joan P. Avatar

Hi there! When I truy to create my page I recieve this error
The controller for URI "/" is not callable: Controller "App\Controller\DefaultController" does neither exist as service nor as class.

Do I have something not installed properly?
Thanks

Reply

Hey Joan P.

Did you uncomment the lines inside of config/routes.yaml?

Reply
Simon L. Avatar
Simon L. Avatar Simon L. | posted hace 2 años

Hi there !

When I do ./bin/console debug:router I can see 2 routes with same path, is it normal ?

app_homepage ANY ANY ANY /
index ANY ANY ANY /

Reply

Hey Simon L.!

Hmm, not normal! But good job noticing that :).

One of those (app_homepage) is coming from the annotations routes in your controller and the other (index) is coming from your config/routes.yaml file (I know because I remember that the default route in that file is just called "index"). When we switch to annotation routes in chapter 4 - https://symfonycasts.com/sc... - make sure you comment-out the YAML routes to avoid the duplicate - https://symfonycasts.com/sc...

Let me know if that helps!

Cheers!

1 Reply
Simon L. Avatar

Hi !

Thanks ! Works perfectly now :)

Reply
Iheb Z. Avatar

When i write
Return new reponse it didnt show me (Symfony\Component\HttpFoundation\Response)
He just showed me the 2 first types in ur tuto

Reply

Hey Iheb Z.!

Hmm. That seems super odd. There is no reason that Symfony\Component\HttpFoundation\Response should not be in your project. I would try 2 things:

1) Manually remove the vendor/ directory and re-run composer install. See if that helps
2) Invalidate the cache in PhpStorm - you can do that at File -> "Invalidate Caches / Restart"

Let me know if that helps!

Cheers!

1 Reply
Iheb Z. Avatar

Ty for your help but I have the same problem.
Here you can find my files. you can check them, maybe I did a mistake.
https://drive.google.com/dr...

Reply

Hey Iheb Z.

Make sure that you have the following PHPStorm plugins installed and up to date
- Symfony Support
- PHP Annotations
- PHP Toolbox

Cheers!

Reply
Iheb Z. Avatar

Hey @Diego Aguiar

Ty for your support
yes it's already installed i watched chapter 1&2 and i did everything!

To ignore that error and keep watching tutos i just selected the type1 in response suggestions and added the use ... code manually it worked .

Cheers!

Reply

Well, at least it's working ;)
I believe it's a problem with PHPStorm, if you could update it, it may help

1 Reply
Christoph Avatar
Christoph Avatar Christoph | posted hace 2 años

Edit: SOLVED

Hi.
I have a question/problem about the required parameter in the new Response(string) or the $this->render(string $view, ... , ....).

My phpStorm shows, that i dont need a "string" but rather a Symfony\Bundle\FrameworkBundle\Controller\string .

The complete Messages are:
for new Response():
Expected Symfony\Component\HttpFoundation\string|void, got string
Inspection Info: Invocation parameter types are not compatible with declared

For $this->render():
Expected \Symfony\Bundle\FrameworkBundle\Controller\string, got string
Inspection Info: Invocation parameter types are not compatible with declared

What is happening there? Why is my phpStorm showing such a thing?
I am very confused, i also looked at the AbstractController to see what it requires and ... sure, it requires (only) a "string" as parameter.
( protected function render(string $view, array.......)

There is something more happening in the AbstractController.
My phpStorm is showing several errors, for example:
protected function createNotFoundException(string $message = 'Not Found',.....) .... here it shows the following error: "Default value for parameters with a class type can only be NULL".

I am using PHP 7.2, my phpStorm is 2019.1.2

Thanks for help
Greetings Chris

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.3.0 || ^8.0.0",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "easycorp/easy-log-handler": "^1.0.7", // v1.0.9
        "sensio/framework-extra-bundle": "^6.0", // v6.2.1
        "symfony/asset": "5.0.*", // v5.0.11
        "symfony/console": "5.0.*", // v5.0.11
        "symfony/debug-bundle": "5.0.*", // v5.0.11
        "symfony/dotenv": "5.0.*", // v5.0.11
        "symfony/flex": "^1.3.1", // v1.17.5
        "symfony/framework-bundle": "5.0.*", // v5.0.11
        "symfony/monolog-bundle": "^3.0", // v3.5.0
        "symfony/profiler-pack": "*", // v1.0.5
        "symfony/routing": "5.1.*", // v5.1.11
        "symfony/twig-pack": "^1.0", // v1.0.1
        "symfony/var-dumper": "5.0.*", // v5.0.11
        "symfony/webpack-encore-bundle": "^1.7", // v1.8.0
        "symfony/yaml": "5.0.*" // v5.0.11
    },
    "require-dev": {
        "symfony/profiler-pack": "^1.0" // v1.0.5
    }
}
userVoice