gstreamer0.10-ffmpeg
gstreamer0.10-plugins-good
packages.
The page we're looking at right now... which is super fun... and even changes colors... is just here to say "Hello!". Symfony is rendering this because, in reality, our app doesn't have any real pages yet. Let's change that.
Every web framework... in any language... has the same main job: to give you a route & controller system: a 2-step system to build pages. A route defines the URL of the page and the controller is where we write PHP code to build that page, like the HTML or JSON.
Open up config/routes.yaml
:
#index: | |
# path: / | |
# controller: App\Controller\DefaultController::index |
Hey! We already have an example! Uncomment that. If you're not familiar with YAML, it's super friendly: it's a key-value config format that's separated by colons. Indentation is also important.
This creates a single route whose URL is /
. The controller points to a function that will build this page... really, it points to a method on a class. Overall, this route says:
when the user goes to the homepage, please execute the
index
method on theDefaultController
class.
Oh, and you can ignore that index
key at the top of the YAML: that's an internal name for the route... and it's not important yet.
The project we're building is called "Cauldron Overflow". We originally wanted to create a site where developers could ask questions and other developers answered them but... someone beat us to it... by... like 10 years. So like all impressive startups, we're pivoting! We've noticed a lot of wizards accidentally blowing themselves up... or conjuring fire-breathing dragons when they meant to create a small fire for roasting marshmallows. And so... Cauldron Overflow is here to become the place for witches and wizards to ask and answer questions about magical misadventures.
On the homepage, we will eventually list some of the most recent questions. So let's change the controller class to QuestionController
and the method to homepage
.
index: | |
path: / | |
controller: App\Controller\QuestionController::homepage |
Ok, route done: it defines the URL and points to the controller that will build the page. Now... we need to create that controller! Inside the src/
directory, there's already a Controller/
directory... but it's empty. I'll right click on this and select "New PHP class". Call it QuestionController
.
Ooh, check this out. It pre-filled the namespace! That's awesome! This is thanks to the Composer PhpStorm configuration we did in the last chapter.
Here's the deal: every class we create in the src/
directory will need a namespace. And... for reasons that aren't super important, the namespace must be App\
followed whatever directory the file lives in. Because we're creating this file in the Controller/
directory, its namespace must be App\Controller
. PhpStorm will pre-fill this every time.
... lines 1 - 2 | |
namespace App\Controller; | |
... lines 4 - 6 | |
class QuestionController | |
{ | |
... lines 9 - 12 | |
} |
Perfect! Now, because in routes.yaml
we decided to call the method homepage
, create that here: public function homepage()
.
... lines 1 - 2 | |
namespace App\Controller; | |
... lines 4 - 6 | |
class QuestionController | |
{ | |
public function homepage() | |
{ | |
... line 11 | |
} | |
} |
And.. congratulations! You are inside of a controller function, which is also sometimes called an "action"... to confuse things. Our job here is simple: to build the page. We can write any code we need to do that - like to make database queries, cache things, perform API calls, mine cryptocurrencies... whatever. The only rule is that a controller function must return a Symfony Response
object.
Say return new Response()
. PhpStorm tries to auto-complete this... but there are multiple Response
classes in our app. The one we want is from Symfony\Component\HttpFoundation
. HttpFoundation is one of the most important parts - or "components" - in Symfony. Hit tab to auto-complete it.
But stop! Did you see that? Because we let PhpStorm auto-complete that class for us, it wrote Response
, but it also added the use
statement for this class at the top of the file! That is one of the best features of PhpStorm and I'm going to use it a lot. You will constantly see me type a class and allow PhpStorm to auto-complete it so that it adds the use
statement to the top of the file for me.
Inside new Response()
, add some text:
What a bewitching controller we have conjured!
... 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!'); | |
} | |
} |
And... done! We just created our first page! Let's try it! When we go to the homepage, it should execute our controller function... which returns the message.
Find your browser. We're already on the homepage... so just refresh. Say hello to our very first page. I know, it's not much to look at yet, but we've already covered the most foundational part of Symfony: the route and controller system.
Next, let's make our route fancier by using something called annotations. We'll also create a second page with a route that matches a wildcard path.
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!
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!
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 withsymfony new <project_name> --version=5.0
Cheers
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!
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!
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.
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!
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
Hi @Andreas
Can you please share your controller code? It's pretty hard to say something without seeing real code =)
Cheers
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');
}
}
`
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');
}
}`
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!
I have Symfony plugin. I checked it on site. It doesnt work. I have still Symfony homepage instead of my words
Oh, I just noticed that you forgot to add the Route annotations on top of your homepage() method. Give it a try
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.
`
/**
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
`
/**
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.
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!
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 ?
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!
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
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']
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
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! :)
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.*"
}
}
It could be, I'd re-install the vendors directory, and double-check the file name and namespace of the QuestionController
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 ?
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
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
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!
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.
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
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 !
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!
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!
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.
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!
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
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 /
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!
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
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!
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...
Hey Iheb Z.
Make sure that you have the following PHPStorm plugins installed and up to date
- Symfony Support
- PHP Annotations
- PHP Toolbox
Cheers!
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!
Well, at least it's working ;)
I believe it's a problem with PHPStorm, if you could update it, it may help
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
// 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
}
}
in my route.ymal I don't know where i put my method :