Chapters
-
Course Code
Subscribe to download the code!
Subscribe to download the code!
-
This Video
Subscribe to download the video!
Subscribe to download the video!
-
Subtitles
Subscribe to download the subtitles!
Subscribe to download the subtitles!
-
Course Script
Subscribe to download the script!
Subscribe to download the script!
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
¡Bienvenido de nuevo, equipo, al tercer episodio de nuestra serie Symfony 6! Los dos primeros cursos han sido súper importantes: nos han llevado desde los fundamentos hasta el núcleo de cómo funciona todo en Symfony: todo lo bueno de los "servicios" y la configuración. Ahora estás preparado para utilizar cualquier otra parte de Symfony y empezar a construir realmente un sitio.
Y... ¿qué mejor manera de hacerlo que añadir una base de datos? Porque... hasta ahora, a pesar de todas las cosas geniales que hemos hecho, el sitio que hemos estado construyendo es 100% estático ¡Aburrido! Es hora de cambiar eso.
Hola Doctrine
Sabemos que Symfony es una colección de un montón de bibliotecas para resolver un montón de problemas diferentes. Entonces... ¿tiene Symfony algunas herramientas para ayudarnos a hablar con la base de datos? La respuesta es... ¡no! Porque... ¡no tiene que hacerlo!
¿Por qué? Entra Doctrine: la biblioteca más potente del mundo PHP para trabajar con bases de datos. Y Symfony y Doctrine funcionan muy bien juntos: son los Frodo y Sam Gamgee de la Tierra Media de PHP: los Han Solo y Chewbacca de la Alianza Rebelde de PHP. Symfony y Doctrine son como dos personajes de Disney que se acaban los bocadillos el uno al otro
Configuración del proyecto
Para ver este dúo dinámico en acción, vamos a configurar nuestro proyecto. Jugar con las bases de datos es divertido, ¡así que codifica conmigo! Hazlo descargando el código del curso desde esta página. Tras descomprimirlo, encontrarás un directorio start/
con el mismo código que ves aquí. Abre este archivo README.MD
para obtener todas las instrucciones de configuración.
El último paso será abrir un terminal, entrar en tu proyecto y ejecutar:
symfony serve -d
Esto utiliza el binario de Symfony para iniciar un servidor web local que vive en https://127.0.0.1:8000. Tomaré el camino más perezoso y haré clic en eso para ver... ¡Vinilo mezclado! Nuestra última idea de startup -y te juro que va a ser enorme- combina la nostalgia de las "cintas de mezcla" de los años 80 y 90 con la experiencia de audio de los discos de vinilo. Tú creas tus dulces cintas de mezcla, y nosotros las prensamos en un disco de vinilo para obtener una experiencia de audio totalmente hipster.
Hasta ahora, nuestro sitio tiene una página de inicio y una página para navegar por las mezclas que han creado otras personas. Sin embargo, esa página no es realmente dinámica: se extrae de un repositorio de GitHub... y a menos que hayas configurado una clave API como hicimos en el último episodio, ¡esta página está rota! Eso es lo primero que vamos a arreglar: consultar una base de datos para las mezclas.
Instalar Doctrine
¡Así que vamos a instalar Doctrine! Busca tu terminal y ejecútalo:
composer require "doctrine:^2.2"
Esto es, por supuesto, un alias de Flex para una biblioteca llamada symfony/orm-pack
. Y recuerda: un "paquete" es una especie de "biblioteca falsa" que sirve como atajo para instalar varios paquetes a la vez. En este caso, estamos instalando el propio Doctrine, pero también algunas otras bibliotecas relacionadas, como el excelente sistema Doctrine Migrations.
Configuración de Docker
Ah, y ¡mira esto! El comando pregunta:
¿Quieres incluir la configuración Docker de las recetas?
Así, ocasionalmente, cuando instales un paquete, la receta de ese paquete contendrá la configuración de Docker que puede, por ejemplo, iniciar un contenedor de base de datos. Esto es totalmente opcional, pero voy a decir p
por sí mismo permanentemente. Hablaremos más sobre la configuración Docker en unos minutos.
Las recetas de Doctrine
Pero ahora mismo, vamos a comprobar lo que hizo la receta. Ejecuta:
git status
Muy bien: esto modificó los archivos normales como composer.json
, composer.lock
ysymfony.lock
... y también modificó config/bundles.php
. Si lo compruebas... no es ninguna sorpresa: nuestra aplicación tiene ahora dos nuevos bundles: DoctrineBundle y DoctrineMigrationsBundle.
Pero probablemente la parte más importante de la receta es el cambio que se ha realizado en nuestro archivo.env
. Recuerda: aquí es donde podemos configurar las variables de entorno... y la receta nos dio una nueva llamada DATABASE_URL
. Ésta, como puedes ver, contiene todos los detalles de la conexión, como el nombre de usuario y la contraseña.
¿Qué utiliza esta variable de entorno? ¡Excelente pregunta! Mira el nuevo archivo que nos dio la receta: config/packages/doctrine.yaml
. La mayor parte de esta configuración no tendrás que pensarla ni cambiarla. Pero fíjate en esta clave url
: ¡lee la variable de entorno DATABASE_URL
!
La cuestión es: la variable de entorno DATABASE_URL
es la clave para configurar tu aplicación para que hable con una base de datos... y jugaremos con ella en unos minutos.
La receta también ha añadido unos cuantos directorios nuevos: migrations/
src/Entity/
ysrc/Repository/
. Ahora mismo, aparte de un archivo .gitignore
sin sentido, están todos vacíos. Pronto empezaremos a llenarlos.
Bien: Doctrine ya está instalado. Pero para hablar de una base de datos... tenemos que asegurarnos de que tenemos una base de datos en funcionamiento y que la variable de entorno DATABASE_URL
apunta a ella. Hagamos eso a continuación, pero con un giro opcional y delicioso: vamos a utilizar Docker para iniciar la base de datos.
23 Comments
Hey @SoftwareDevs ,
There's a workaround on that thread you linked, probably you will need to go with that. I personally didn't have that issue, so I don't have a better workaround. It sounds like an issue in a specific version. You can track the status of the issue on that thread I think.
Cheers!
Hello there !
when I try to open the downloaded source files I get this error from Symfony: Environment variable not found: "GITHUB_TOKEN". I'm not sure how to fix it
Hey @Ted
Could you corroborate you got that error from the code project of this tutorial? Also, does it happen on both directories (start, finish)? I'm asking because I just checked this course project and there are not any references to such environment variable
yes from the code project of this tutorial, it actually happens on both (start and finish) it also happens on the projects I tried to download form the next episodes in this tutorial, I followed along with Ryan since the first course and I started getting this error around the last episodes of the last course and I couldnt't solve it since. I'm following along with two computers to do the work twice and understand better but now I'm getting the error on both computers.
That's odd, I just gave it a try and could install the start
directory of this project without any problems. This makes me think there's something going on in your local machine. Let's try to find where is that env var being used, run: git grep GITHUB_TOKEN
As a workaround, just define the env var in the .env
file and try again
It's odd, i had the same issue today.
Interesting, thank you for reporting it @Stanislaw
I'll look deeper and fix the tutorial's code, in the meanwhile, you can go with my workaround
Cheers!
it is quite odd indeed, defining the variable in the .env file did the work. thank you
Hi there!
The env var is used in config/packages/framework.yaml
when you download the course code - so that part isn't surprising. So then, where is it defined? In the previous episode, we added it to the "secrets vault" - and the dev (and prod) secrets vault IS included in the download - e.g. it's config/secrets/dev/dev.GITHUB_TOKEN.28bd2f.php
. You should be able to see the secret by running:
php bin/console secrets:list --reveal
Anything in your secrets vault becomes an environment variable. So, this part is the mystery I think: why the GITHUB_TOKEN
seems to be missing? Do you see it in the list when you run the above command (it should actually be the only env var returned in the list)? I have a feeling that your system may be missing the "sodium" PHP extension, which is normally part of core php, but I think some Linux distros may ship PHP without it (and then you can install it manually). Let me know if that's the case!
Cheers!
I had the same issue and installed the sodium extension by running
composer require paragonie/sodium_compat
It worked!
Hello there!
I got a weird problem I don't know how to solve. Working on Symfony's project in version 6.2, and PHP 8.2 after running composer require doctrine
errors occur:
- symfony/orm-pack[v1.0.0, ..., v1.0.7] require php ^7.0 -> your php version (8.2.3) does not satisfy that requirement.
- doctrine/doctrine-migrations-bundle[v2.0.0, ..., 2.2.1] require php ^7.1 -> your php version (8.2.3) does not satisfy that requirement.
- doctrine/orm[v2.6.0, ..., 2.7.5] require php ^7.1 -> your php version (8.2.3) does not satisfy that requirement.
And more...
I know what that means, but do you have any ideas on how to solve that in a different way than downgrading my PHP version?
When I run composer require "symfony/orm-pack:^2.3"
, another errors are shown:
- doctrine/orm[2.3.0, ..., v2.3.6] require symfony/console 2.* -> found symfony/console[2.0.4, ..., v2.8.52] but it conflicts with your root composer.json require (6.2.*).
- doctrine/orm[v2.4.0, ..., v2.4.8] require symfony/console ~2.0 -> found symfony/console[2.0.4, ..., v2.8.52] but it conflicts with your root composer.json require (6.2.*).
- doctrine/orm[v2.5.0, ..., v2.5.1] require symfony/console ~2.5 -> found symfony/console[v2.5.0, ..., v2.8.52] but it conflicts with your root composer.json require (6.2.*).
Thanks!
Hey Bartlomeij,
I don't think there're any other robust solutions. You can try to ignore platform requirements with --ignore-platform-reqs
flag, but I'd not recommend it because it may cause issues in your code as it will use the new PHP syntax that will just not work on your PHP version.
So, you need either downgrade your PHP version or upgrade those required packages to a newer (most probably major) version. You can leverage https://packagist.org/ to see what version of the package requires what PHP version.
I hope this helps!
Cheers!
Hi there,
It is not clear for me if the composer install should be run inside the "start" directory or outside
When I install it inside the directory it works better than outside.
Howdy Benoit -
When I install it inside the directory it works better than outside.
This made me chuckle :) But to answer your question, yes - run composer install
inside the start
directory.
From this point on, you'll be doing everything from within the start
directory. The finish
directory is how your code should look at the end of the tutorial - assuming you're coding along with Ryan throughout the course.
Enjoy!
Yes, I think it would make me chuckle as well if I would read something like that :)
Could you take into consideration the way it is presented in the ReadMe file ?
Step 1 : (in whatever directory you are you should check that composer is installed properly)
So I would say that you should already mention that you are in the directory of your project at this stage.
In the Readme you are saying that you should only move to the directory later : "once on your system.
Then, to start the web server, open a terminal, move into theproject, and run ...":
Make sure you have Composer installed
and then run:
composer install
You may alternatively need to run php composer.phar install
, depending
on how you installed Composer.
Start the Symfony web server
You can use Nginx or Apache, but Symfony's local web server
works even better.
To install the Symfony local web server, follow
"Downloading the Symfony client" instructions found
here: https://symfony.com/download - you only need to do this
once on your system.
Then, to start the web server, open a terminal, move into the
project, and run:
symfony serve
The problem is also that when I run git status I have a lot of files that are displayed and that should not be, right ?
Sorry for the slow reply,
Once you've extracted and moved into the start
directory, you should be able to git init
to initialize that directory as a git repository. git add .
then git commit -m "starting the tutorial"
to add and commit everything in start
to the repo. Now when you run composer install
, you will see a few files change - like composer.lock
and possibly see a couple files added/changed due to Symfony's Flex recipe system. Those changes are ok to commit after running composer. Thanks to .gitignore
you shouldn't see anything in git status
related to say vendor/
and the like.
Does that sound about right for what you're seeing?
Hi when following along, git status doesn't work because of course there is no git repo... I'm thinking we should run git init after composer install and before composer require "doctrine:^2.2"
Hey Markchicobaby!
git status doesn't work because of course there is no git repo
Ha! Of course! I've been saying this type of thing for years without thinking about this fact! The hope is that you will initialize the git repository when you start via git init
, but you're absolutely right that I don't say this. I'm going to be more careful with my language afterwards.
Cheers!
Hey! The audio stops at 5:22 and the video froze too!
Hey Craig,
We're sorry to hear you're experiencing problems with our video player! I just double-check it, the video plays well for me around those 5:22, so it might be an internet connection issue on your laptop and so the video was not able to load from the server. Or, it might be a temporary outage of Vimeo video service - our video hosting provider. Please, try again today and let us know if the problem still persist. In this case, as a temporary workaround, I'd recommend you to download the video and watch it locally.
I hope this helps.
Cheers!
The video player still doesn't work for me in the website. The downloaded video works great. I don't have any trouble with any other videos on the site (I've watched dozens), so I assumed it was an issue with this video specifically.
Hey Craig,
Glad to hear you were able to watch the downloaded video in full locally. I'd recommend you to try a different browser, or probably a Chrome Incognito mode might help as well. But since you already watched it locally, you may just ignore :)
I still can't reproduce it for myself, so I think it should be good and most probably it's something local.
Cheers!
"Houston: no signs of life"
Start the conversation!
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": ">=8.1",
"ext-ctype": "*",
"ext-iconv": "*",
"babdev/pagerfanta-bundle": "^3.7", // v3.7.0
"doctrine/doctrine-bundle": "^2.7", // 2.7.0
"doctrine/doctrine-migrations-bundle": "^3.2", // 3.2.2
"doctrine/orm": "^2.12", // 2.12.3
"knplabs/knp-time-bundle": "^1.18", // v1.19.0
"pagerfanta/doctrine-orm-adapter": "^3.6", // v3.6.1
"pagerfanta/twig": "^3.6", // v3.6.1
"sensio/framework-extra-bundle": "^6.2", // v6.2.6
"stof/doctrine-extensions-bundle": "^1.7", // v1.7.0
"symfony/asset": "6.1.*", // v6.1.0
"symfony/console": "6.1.*", // v6.1.2
"symfony/dotenv": "6.1.*", // v6.1.0
"symfony/flex": "^2", // v2.4.5
"symfony/framework-bundle": "6.1.*", // v6.1.2
"symfony/http-client": "6.1.*", // v6.1.2
"symfony/monolog-bundle": "^3.0", // v3.8.0
"symfony/proxy-manager-bridge": "6.1.*", // v6.1.0
"symfony/runtime": "6.4.3", // v6.4.3
"symfony/twig-bundle": "6.1.*", // v6.1.1
"symfony/ux-turbo": "^2.0", // v2.3.0
"symfony/webpack-encore-bundle": "^1.13", // v1.15.1
"symfony/yaml": "6.1.*", // v6.1.2
"twig/extra-bundle": "^2.12|^3.0", // v3.4.0
"twig/twig": "^2.12|^3.0" // v3.4.1
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.4", // 3.4.2
"symfony/debug-bundle": "6.1.*", // v6.1.0
"symfony/maker-bundle": "^1.41", // v1.44.0
"symfony/stopwatch": "6.1.*", // v6.1.0
"symfony/web-profiler-bundle": "6.1.*", // v6.1.2
"zenstruck/foundry": "^1.21" // v1.21.0
}
}
Hello there! HELP!
Recently I've migrated from Symfony 5.4 to Symfony 6.4 (64.10), with this upgrade doctrine/orm and doctrine/doctrine-migrations-bundle also have been upgraded:
The problem is when I try to validate the schema:
php bin/console doctrine:schema:validate -v
I got this error:
DROP TABLE doctrine_migration_versions;
I've found an open issue in GitHub: https://github.com/doctrine/migrations/issues/1406
But I would like to know is someone else could fix the issue and how?