Chapters
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
Uno de mis objetivos principales en este tutorial será ayudarte a entender realmente cómo funciona Symfony, tu aplicación.
Para empezar, echemos un vistazo a la estructura de carpetas.
El Directorio public/
Hay solo 3 directorios que debes tener en cuenta. Primero, public/
es el documento raíz: el cual contendrá todos los archivos que deben ser accesibles por un navegador. Y... por ahora hay uno solo: index.php
:
Show Lines
|
// ... lines 1 - 2 |
use App\Kernel; | |
use Symfony\Component\ErrorHandler\Debug; | |
use Symfony\Component\HttpFoundation\Request; | |
require dirname(__DIR__).'/config/bootstrap.php'; | |
if ($_SERVER['APP_DEBUG']) { | |
umask(0000); | |
Debug::enable(); | |
} | |
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) { | |
Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); | |
} | |
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) { | |
Request::setTrustedHosts([$trustedHosts]); | |
} | |
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']); | |
$request = Request::createFromGlobals(); | |
$response = $kernel->handle($request); | |
$response->send(); | |
$kernel->terminate($request, $response); |
Éste se llama el "front controller": un término complejo que los programadores inventaron para decir que este archivo es el que ejecuta tu servidor web.
Pero, en realidad, salvo poner archivos CSS o imágenes en public/
, casi nunca tendrás que pensar en ello.
src/ y config/
Así que... En realidad te mentí. Hay en verdad sólo dos directorios que debes tener en cuenta: config/
y src/
. config/
tiene... ehh... perritos? No, config/
tiene archivos de configuración y src/
es donde tu código PHP estará. Es así de simple.
Dónde está Symfony? Nuestro proyecto comenzó con un archivo composer.json
:
{ | |
"type": "project", | |
"license": "proprietary", | |
"require": { | |
"php": "^7.2.5", | |
"ext-ctype": "*", | |
"ext-iconv": "*", | |
"symfony/console": "5.0.*", | |
"symfony/dotenv": "5.0.*", | |
"symfony/flex": "^1.3.1", | |
"symfony/framework-bundle": "5.0.*", | |
"symfony/yaml": "5.0.*" | |
}, | |
"require-dev": { | |
}, | |
Show Lines
|
// ... lines 16 - 64 |
} |
el cual contiene todas las librerías de terceros que nuestra aplicación necesita. Detrás de escenas, el comando symfony new
utilizó a composer para instalarlas... Lo cual es una forma sofisticada de decir que Composer descargó un montón de librerías dentro del directorio vendor/
... Incluyendo Symfony.
Más adelante hablaremos de los otros archivos y directorios, pero éstos todavía no nos importan.
Utilizando el Servidor Web Local de Symfony
Hace algunos minutos, usamos PHP para iniciar un servidor web local. Bien. Pero presiona Ctrl+C para salir del mismo. Por qué? Porque esa herramienta binaria symfony que instalamos viene con un servidor local mucho mas poderoso.
Ejecuta:
symfony serve
Eso es todo. La primera vez que lo corres, podría preguntarte sobre instalar un certificado. Esto es opcional. Si lo instalas - yo lo hice - iniciará el servidor web con https. Sip, tienes https local con cero esfuerzo. Una vez que corre, ve a tu navegador y refresca. Funciona! Y ese pequeño candado prueba que estamos usando https.
Para parar el servidor, solo presiona Control + C. Puedes ver todas estas opciones de comando al ejectuar:
symfony serve --help
Como por ejemplo, formas de controlar el número de puerto
Cuando uso este comando, usualmente corro:
symfony serve -d
-d significa correr como un daemon. Hace exactamente lo mismo excepto que ahora corre en segundo plano... Lo que significa que puedo seguir usando esta terminal. Si corro:
symfony server:status
Me muestra que el servidor está corriendo y
symfony server:stop
Lo apagará. Iniciemoslo de nuevo:
symfony serve -d
Instalando Plugins de PhpStorm
Ok: estamos a punto de comenzar a escribir un montón de código... ai que quiero asegurarme de que tu editor está listo para trabajar. Y, claro, puedes usar cualquier editor que tu quieras. Pero mi mejor recomendación es PhpStorm! En serio, hace que desarrollar en Symfony sea un sueño! Y no, las buenas personas de PhpStorm no me están pagando para decir esto... aunque... sí patrocinan a varios desarrolladores de código libre en PHP... lo que lo hace aún mejor.
Para tener un fantástico PhpStorm, tienes que hacer dos cosas. Primero, abre Preferencias, selecciona "Complementos" y click en "Marketplace". Haz una búsqueda por "Symfony". Este plugin es increíble... probado por casi 4 millones de descargas. Esto nos dará toda clase de auto-completes e inteligencia extra para Symfony.
Si no lo tienes aún, instálalo. Deberías también instalar los plugins "PHP Annotations" y "PHP toolbox". Si realizas una búsqueda por "php toolbox"... puedes ver los tres de ellos. Instálalos y luego reinicia PhpStorm.
Una vez reiniciado, vuelve a Preferencias y haz una búsqueda por Symfony. Además de instalar este plugin, tienes que habilitarlo en cada proyecto. Haz click en Habilitar y luego Aplicar. Dice que tienes que reiniciar PhpStorm... pero no creo que eso sea necesario.
La segunda cosa que tienes que hacer en PhpStorm es buscar Composer y encontrar la sección "Idiomas y Frameworks", "PHP", "Composer". Asegúrate de que la opción "Sincronizar ajustes IDE con composer.json" está activada... lo cual automáticamente configura algunas funciones útiles.
Haz click en "Ok" y... estamos listos! A continuación, vamos a crear nuestra primerísima página y veremos de qué se trata symfony.
57 Comments
Hey Samuel S.!
> My php storm is not bringing out the full prediction when I'm typing
> Return new response
Hmmm. This is one of the most basic features that PhpStorm gives you, so it definitely makes me think something is wrong. Two questions:
1) Does the code work? If you add the use statement and type all the code, does it work? That will help answer the question of whether or not all the vendor code is installed correctly.
2) How did you open PhpStorm? I usually go to "File -> Open" and select my entire Symfony directory. After you do this, you should see all the folders - like config/, src/ and public/ - on the left tree. If you somehow only opened a *specific* file (not the entire directory), then you would probably not get auto-complete.
> I also noticed that your initial command (symfony new cauldron_overflow) is not working
Hmm, did you get an error when you ran this? Do you remember what the error was?
Don't worry, I'm sure we'll figure out what's going on :).
Cheers!
I've seen my mistake.
I always write response with a lowercase r instead of uppercase like so: ' Response'
Your response time is impressive.
Thank you very much.
Cheers.
Ah... good catch! Thanks for letting me know - I'll put that on my "list of things that might be preventing auto-complete" to think about!
Cheer!
1. Yes, the code works when I manually input the use statement.
2. I open the the entire symfony folder.
After symfony server:ca:install it makes the connection insecure in Chrome.
Hey Folza,
Make sure you open https://127.0.0.1:8000/ by the HTTPS protocol instead of HTTP :)
Cheers!
Hi guys !
I just followed your videos and just after generating the project I got that issue when I run the server :
Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "No route found for "GET http://localhost:8000/"" at C:\{My path}\app\vendor\symfony\http-kernel\EventListener\RouterListener.php line 130
I tried to create the (full) project with composer instead of symfony CLI but same problem.
Could someone help me ? Thx !!
Hey Pierre Lds!
Hmm, that's not what we want! Well, it *kind* of is :). After you first create a project, it's true that you don't have any "routes" yet and so if you go to the homepage, then you *should* get no matching route (which is what your error means). However, Symfony has a nice feature for this situation where it shows you that "welcome page" if you have this situation. So I'm not sure why you're not seeing that!
I've just started a new (Symfony 6) project with the symfony binary... and I see the welcome page just fine. So this is a mystery to me - I can't explain what's happening? I guess I would ignore it and keep coding, as the welcome back isn't *needed*. But keep an eye out for anything else weird, and let me know if you see anything.
Cheers!
Hi people, only a question! Could I install this certificate in a Docker environment?
Hey vespino_rojo
That's a good question. I'm not totally sure if it works out of the box but Symfony has Docker support, you only need to run your console commands through Symfony's binarysymfony serve -d
That will set up the env vars properly. You can read a bit more here https://symfony.com/doc/current/setup/symfony_server.html#symfony-server-docker
Cheers!
Hello,
could you do some elasticsearch and symfony lessons
Hey Nizar
Yep we have this course on our list, but I can't provide any details when it will be released!
Cheers!
Hi, thanks for the great work !
I have an issue when I use the symfony local web server. I run this command:
symfony serve
And I get this output:
`
Tailing Web Server log file (/home/user/.symfony/log/a07f55e8aab485bac93249e125f7fa400b627b3f.log)
Tailing PHP log file (/home/user/.symfony/log/a07f55e8aab485bac93249e125f7fa400b627b3f/7daf403c7589f4927632ed3b6af762a992f09b78.log)
[OK] Web server listening
The Web server is using PHP CLI 7.4.3
https://127.0.0.1:8000
[Web Server ] Apr 17 18:31:40 |DEBUG | PHP Reloading PHP versions
[Web Server ] Apr 17 18:31:40 |DEBUG | PHP Using PHP version 7.4.3 (from default version in $PATH)
[PHP ] [Sat Apr 17 18:31:40 2021] PHP 7.4.3 Development Server (http://127.0.0.1:45781) started
[Web Server ] Apr 17 18:31:40 |INFO | PHP listening path="/usr/bin/php7.4" php="7.4.3" port=45781
`
The problem is that when I try to access https://127.0.0.1:8000 in my browser, it does not work. I get a "connection failed" error.
But it actually works when I access this url: http://127.0.0.1:45781
Do you have any idea about what is wrong in my setup ?
Thanks :)
Hey Aurelien A.
Have you tried to load http://127.0.0.1:8000
? If it works, then it's problem with local ssl certificates. You have two possible scenarios:
- Use http in dev mode with
symfony serve --no-tls
- Try to fix it with
symfony server:ca:install
and try again with https
Cheers
Hey,
Thanks for the answer. Yes I also tried http://127.0.0.1:8000
but unfortunately it is not working.
What about re installing certificates or running symfony server without tls?
Hey, sorry for the late answer. This is not working either.This is the ouput when I run symfony server:start --no-tls
<blockquote>Tailing Web Server log file (/home/user/.symfony/log/a07f55e8aab485bac93249e125f7fa400b627b3f.log)
Tailing PHP log file (/home/user/.symfony/log/a07f55e8aab485bac93249e125f7fa400b627b3f/7daf403c7589f4927632ed3b6af762a992f09b78.log)
[OK] Web server listening
The Web server is using PHP CLI 7.4.3
http://127.0.0.1:8000
[Web Server ] Apr 28 18:52:54 |DEBUG | PHP Reloading PHP versions
[Web Server ] Apr 28 18:52:55 |DEBUG | PHP Using PHP version 7.4.3 (from default version in $PATH)
[Web Server ] Apr 28 18:52:55 |INFO | PHP listening path="/usr/bin/php7.4" php="7.4.3" port=42001
[PHP ] [Wed Apr 28 18:52:55 2021] PHP 7.4.3 Development Server (http://127.0.0.1:42001) started
</blockquote>
re installing certificates does not change anything either.
It is still working on http://127.0.0.1:42001, but this is inconveniant because when I want to try routes with Postman for example I have to change my base url port everytime I start the local web server
weird....What OS are you using? And how have you installed your php? some path looks weird to me so I need more info about your env to help
As suggestion to test have you tried to run native php server? with php -S 127.0.0.1:8000 -t ./public
from your project folder?
Cheers and sorry for late answer 😊
Hey,
Sorry for the late answer too
I am using Windows 10 with WSL 2. I launch the server from wsl 2 terminal (ubuntu 20.04). php native server is working !
php -S 127.0.0.1:8000 -t ./public
[Mon May 10 17:12:23 2021] PHP 7.4.3 Development Server (http://127.0.0.1:8000) started
[Mon May 10 17:12:29 2021] 127.0.0.1:40662 Accepted
[Mon May 10 17:12:32 2021] 127.0.0.1:40662 [404]: GET /
[Mon May 10 17:12:32 2021] 127.0.0.1:40662 Closing
[Mon May 10 17:12:32 2021] 127.0.0.1:40664 Accepted
[Mon May 10 17:12:33 2021] 127.0.0.1:40664 [200]: GET /_wdt/7464bd
[Mon May 10 17:12:33 2021] 127.0.0.1:40664 Closing
[Mon May 10 17:12:33 2021] 127.0.0.1:40666 Accepted
Tell me if you need more info :)
Cheers
woh my guess is that WSL2 is not fully compatible with symfony binary...as a solution try to install php-fpm package on ubuntu, this may solve your issue with symfony server... I hope it will solve it =)
Cheers!
Hey,
I tried something I should've try a long time ago. I used curl to check if I could access https://127.0.0.1:8000 and it worked, so I knew the problem came from my browser.
Then, I tried https://localhost:8000/ on my browser and it worked ! https://127.0.0.1:8000 is still not working, but it is fine. I don't really know why it didn't work but I am glad I found a solution.
Thank you for your time !
That is very strange... I'm happy that you found this solution and shared info with us!
Keep learning! Cheers!
Hi, great tutorials!
I was wondering about installing an SSL certificate with "symfony server:ca:install"
Because I am usually working from a standard user account on my mac, I cannot use this command. Sure, I can log as admin and install it there, but then the certificate is local, right? So I cannot use it in my standard account.
Any workarounds to installing this certificate on my standard account?
Thanks!
Hey Georg,
Difficult to say, do you have any errors when you're trying to install the certs when you're on behalf of your standard user account?
> Sure, I can log as admin and install it there, but then the certificate is local, right?
Unfortunately, I'm not sure how it works internally, but you can probably try, why not? It might work. Also, you can take a look at "--p12" option for "symfony serve" command, from its description it says "Certificate path (p12 format)" - so it might work I suppose, you can try to install the certs from the admin user and try to reference to them with this option. You probably would need to change the owner of them get the access from your standard user, or probably even move them to a public dir - though not sure if it's secure or no :)
> Any workarounds to installing this certificate on my standard account?
Workarounds - well, do not use HTTPS probably. You can run the webserver with:
$ symfony serve --no-tls
This way the website will be available via HTTP only.
I hope this helps!
Cheers!
Hi there,
my project has been growing for some time. I start the server with `symfony serve --no-tls` and get the message:
"Tailing PHP log file (/home/georg/.symfony/log/df57c473ebee3810bfb1dcf72982d4afc7f35e5b/7daf403c7589f4927632ed3b6af762a992f09b78.log)"
Each time I start the server there are more of these (identical) lines. At the moment about 80. This is just an inconvenience, but possibly something is wrong with the setup?!
Hey Georg,
It seems like a new feature in Symfony built-in web server. For me it looks like this:
Tailing Web Server log file (/Users/victor/.symfony/log/b3fd8c54109f8b0e07dcd737c5262b5d0567b392.log)
Tailing PHP-FPM log file (/Users/victor/.symfony/log/b3fd8c54109f8b0e07dcd737c5262b5d0567b392/53fb8ec204547646acb3461995e4da5a54cc7575.log)
So this is OK, just some extra log files are shown in the output :)
Cheers!
Hey Victor,
ok, thanks for your comment.
Cheers!
Hello for the previous message i finded a solution
└──╼ apt-get install php7.4-curl php7.4-mbstring php7.4-pgsql php7.4-intl
but, it stay this warning, i continue cherching but if you know wat is about, thank you for you help
PHP Warning: Module 'intl' already loaded in Unknown on line 0
Hey Diallo,
Glad to hear you were able to install PDO driver!
Hm, about Intl - looks like it's loaded twice in your PHP config, you need to look at your config and comment out or remove the line where PHP loads it the 2nd time - try to look in your php.ini config. Or, probably try to remove that "php7.4-intl" extra package and try again, it should gone. Probably it was installed and enabled out of the box already for you.
Cheers!
hello i have this issues, please help !!!
PHP Warning: PHP Startup: Unable to load dynamic library 'intl' (tried: /usr/lib/php/20190902/intl (/usr/lib/php/20190902/intl: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/intl.so (/usr/lib/php/20190902/intl.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Hey dialbak
I believe you haven't install the php-intl module on your local environment. If you're on Ubuntu you can do this sudo apt-get install php-intl
Cheers!
Glad to hear it, keep it up!
I can get the PHP web server running just fine on 127.0.0.1:8000 (had to quit Apache, from Filemaker Server that was running, to get it to load on 127.0.0.1:8000). I can't get the PHP webserver to respond on localhost. When I run symfony serve, i get an error - localhost: no such host. I am not sure what I am missing to get the symfony web server running. (Mac OS 10.15.6)
I poked around some more and figure out that I needed to bind localhost to 127.0.0.1. That solved the issue and symfony server is now running.
Hey Wade C.
Weird situation. In most cases localhost IS binded to 127.0.0.1 by default.
Great that you solved this issue and shared result with us.
Cheers
I'm running a lot of different dev tools on my laptop, like a dev copy of Filemaker Server that runs a local webserver. I had to stop FM Server to get Symfony Server to run. Somewhere along the line, one of the dev tools probably unbound localhost.
BTW you can easily change port used by symfony server with --port=8080
;)
Cheers!
I am going back through the tutorial and using it as a guide while I am building a new project. I have another project that I need to start on soon. Can I have a different instance of Symfony server running as a daemon for each project if I set each to a different port number? or do I have to start and stop Symfony serve depending on which project I am working on?
Great question! Of course you can start as much servers as you want =) If you have enough ports and memory to work with =) You can even have .wip
domain names with built-in proxy server, but it's another story =) You can read about it here https://symfony.com/doc/current/setup/symfony_server.html
Hi, i didn't get the https in the command. it is only http. that's means it's not secure.
What can i do to fix that problem?
[OK] Web server listening
http://127.0.0.1:8000
Hey @Shayma
You need to run symfony server:ca:install
to install a local SSL certificate, then you will be able to run your project through https locally
Cheers!
Thank you to help me, i actually repeat everything from the beginning but i have this error:
What is that supposed to mean?
Setting up the project under Git version control
(running git init C:\Users\shaym\cauldron_overflow)
|
*** Please tell me who you are.
Run
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
to set your account's default identity.
Omit --global to set the identity only in this repository.
fatal: unable to auto-detect email address (got 'shaym@LAPTOP-8877L5EN.(none)')
exit status 128
Hey @Shayma!
Ah! That's not a very clear error :). It looks like you're using git for the first time on this system. Try this:
A) Run those 2 comments that it mentioned (the 2 git config commands) but you use real email and name.
B) Re-run the `symfony new</command>
When you first use git on a machine, it asks you to set your name & email. It does this so that when you make any commits, it can use your email and name for those commits. The symfony new
command failed because it tries to setup a git repository for you, but those 2 settings weren't there yet.
Let me know if that helps!
Cheers!
Hey,
Thanks! it's worked when i put my real email. but now i have another issue :( sorry to bothering you!
it says when i run php -s 127.0.0.1:8000 -t public/: Directory public/ does not exist.
And when i do the check:req, it's says that's ok but php need to be installed:
a PHP accelerator should be installed
> Install and/or enable a PHP accelerator (highly recommended).
* realpath_cache_size should be at least 5M in php.ini
> Setting "realpath_cache_size" to e.g. "5242880" or "5M" in
> php.ini* may improve performance on Windows significantly in some
> cases
Can you tell me how to solve this problem?
Hey Shayma,
The better would be to run the project on Symfony web server instead of running built-in PHP web server as you do. If you have symfony binary installed - you just need to run:
$ symfony serve
And it will run the website, then just follow the link in the output.
But in case you want to run the website with PHP built-in web server - looks like the error is pretty obvious, it says the public/ folder does not exist. I suppose you created a new project, but then you should go into the project directory. I.e. after you executed "symfony new my-new-project" Symfony binary created a "my-new-project" folder, so you need to change directory to it, i.e. execute "cd my-new-project" and only then run that "php -s 127.0.0.1:8000 -t public/". When you're in your "my-new-project" directory, to make sure you have public/ folder - you can run "ls public/" command in your terminal.
I hope this helps!
About "check:req" output: if those are just warnings/recommendations - you can completely ignore them for now, the project should run well. But it's recommend to do for production when you will deploy your application for real users. Google how to install PHP accelerator or how to tweak that php.ini config for your OS - it may be different for different OS.
Cheers!
Hey Victor,
Thanks a lot!! You really helped me out. It's working now. I appreciate your help.
Cheers
Hey Shayma,
Great! Thanks for confirming that it works for you now ;)
Cheers!
After running symfony serve -d I'm getting a privacy warning in the browser ('Your connection is not private') and my terminal is showing:
WARNING unable to find the application log
2020/05/12 14:25:20 http: TLS handshake error from 127.0.0.1:55434: remote error: tls: unknown certificate
2020/05/12 14:25:20 http: TLS handshake error from 127.0.0.1:55436: remote error: tls: unknown certificate
2020/05/12 14:25:20 http: TLS handshake error from 127.0.0.1:55442: remote error: tls: unknown certificate
2020/05/12 14:25:20 http: TLS handshake error from 127.0.0.1:55444: remote error: tls: unknown certificate
2020/05/12 14:25:30 http: TLS handshake error from 127.0.0.1:55448: remote error: tls: unknown certificate
2020/05/12 14:25:33 http: TLS handshake error from 127.0.0.1:55450: remote error: tls: unknown certificate
2020/05/12 14:25:33 http: TLS handshake error from 127.0.0.1:55452: remote error: tls: unknown certificate
2020/05/12 14:26:00 http: TLS handshake error from 127.0.0.1:55446: EOF
^CMay 12 14:26:08 |INFO | SERVER shutting down
May 12 14:26:08 |DEBUG| PHP stopped path="/usr/bin/php7.2" php="7.2.24"
May 12 14:26:08 |INFO | SERVER shut down, bye!
It was working when I completed this chapter but after creating the QuestionController in chapter 3 I started getting the above issues. Any help is appreciated
"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.21.6
"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
}
}
My php storm is not bringing out the full prediction when I'm typing
Return new response...
Hence its unable to auto complete the use symfony\component\httpfoundation\response;
Is the problem with the php storm or my installations, I'm using windows and I also noticed that your initial command (symfony new cauldron_overflow) is not working.