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!
Doctrine está ahora configurado para hablar con nuestra base de datos, que vive dentro de un contenedor Docker. Esto es gracias a que el servidor Symfony dev expone esta variable de entorno DATABASE_URL
, que apunta al contenedor. En mi caso, el contenedor es accesible en el puerto 50739.
Ahora vamos a asegurarnos de que la base de datos real se ha creado. Pero primero, en index.php
, elimina el dd()
... y luego cierra ese archivo.
Ve a tu terminal y ejecuta:
php bin/console
Esto imprime todos los comandos de bin/console
que están disponibles, incluyendo un montón de nuevos comandos que empiezan con la palabra doctrine
. Ooh. La mayoría de ellos no son muy importantes y ya iremos viendo los que sí lo son.
bin/console doctrine:database:create
Por ejemplo, uno se llama doctrine:database:create
. Genial, vamos a probarlo:
php bin/console doctrine:database:create
Y... ¡error! Fíjate bien: está intentando conectarse al puerto 5432. ¡Pero nuestra variable de entorno apunta al puerto 50739! Es como si utilizara el valor DATABASE_URL
de nuestro archivo .env
en lugar del real que establece el binario de Symfony.
Y, de hecho, eso es exactamente lo que está ocurriendo. Y, ¡tiene sentido! Cuando actualizamos la página en nuestro navegador, eso se procesa a través del binario symfony
, que le da la oportunidad de añadir la variable de entorno.
Pero cuando ejecutamos un comando bin/console
-donde console
es sólo un archivo PHP que vive en un directorio bin/
, el binario symfony
nunca se utiliza como parte de ese proceso. Esto significa que nunca tiene la oportunidad de añadir la variable de entorno, por lo que Symfony vuelve a utilizar el valor de .env
.
Para solucionar esto, siempre que ejecutemos un comando bin/console
que necesite las variables de entorno de Docker, en lugar de ejecutar bin/console
, ejecuta symfony console
:
symfony console doctrine:database:create
Eso es literalmente un atajo para ejecutar bin/console
: no es diferente. Pero el hecho de que lo estemos ejecutando a través del binario symfony
le da la oportunidad de añadir las variables de entorno.
Cuando probamos esto... ¡sí! Obtenemos un error porque aparentemente la base de datos ya existe, pero se conectó con éxito y habló con la base de datos.
Configurar la versión del servidor
Bien, hay una última parte de la configuración que debemos establecer. Abreconfig/packages/doctrine.yaml
. Este archivo viene de la receta. Buscaserver_version
y desactívalo.
Este valor "13" se refiere a la versión de mi motor de base de datos. Como estoy usando la versión 13 de Postgres, necesito el 13 aquí. Si utilizas MySQL, puede que necesites la 8 o la 5.7.
Esto ayuda a Doctrine a determinar qué características soporta tu base de datos o no... ya que una versión más reciente de una base de datos podría soportar características que una versión más antigua no soporta. No es una pieza de configuración especialmente interesante, sólo tenemos que asegurarnos de que está configurada.
Ok equipo: toda la configuración aburrida está hecha. Lo siguiente: ¡creamos nuestra primera clase de entidad! Las entidades son el concepto más fundamental de Doctrine y la clave para hablar con nuestra primera tabla de la base de datos.
22 Comments
Hey Juergen,
Thanks for pointing it out. You're right, in order to work with the database you'll have to install their correspondent PHP extension, php-pgsql
for Postgres and php-mysql
for MySQL
Cheers!
Hello nice people at SymfonyCasts :)
Got a quick question: Why is that when we use make:entity command and we create non-nullable properties, we will end up having the following in our Entity class:
#[ORM\Column(length: 255)]
private ?string $filename = null;
The above filename property is set to not null during make:entity command process.
We keep adjusting this issue inside our entity files over and over again.
Thank you.
Hello @Ali_M
That's a complex question... in a typed PHP world you should have initialised values before any class manipulations, unfortunately inside Symfony especially with forms there will be lot of errors due to trying access not initialised fields. IIRC it was the cause for this behaviour.
Probably it may be changed sometime, but it requires lot of refactoring
Cheers!
I had an error trying to connect to postresql: An exception occured in the driver: could not find driver and resolved it by removing semicolon ; from php.ini file at lines extension=pdo_pgsql and extension=pgsql.
Hey Stanislaw,
Thank you for sharing this tip with others. Yeah, you need to make sure the DB driver is installed and enabled in your PHP config. Usually, it may happen out of the box but sometimes you need to tweak the config manually, depending on the OS and the way you're installing extensions.
Cheers!
Hello i am still having an error after modifying the ini file..
Hello, make sure you configure the right path in php.ini, in my case I use someting like:extension="C:\Projects\Tutorials\Symfony\php-8.3.4\ext\php_pdo_pgsql"<br />extension="C:\Projects\Tutorials\Symfony\php-8.3.4\ext\php_pgsql"
Also you will see the errors when you run php.exe
Hey Frank,
Make sure you restarted your PHP-FPM in case you use it. If you use Symfony's built-in web server - make sure you restarted it as well to let it read new config parameters. If still the same error - it might be incorrect ini file then. You can find the correct one with php --ini
command.
Cheers!
When running symfony console doctrine:database:create
OR php ./bin/console doctrine:database:create
I get the same error
An exception occurred in the driver: could not find driver
What could it be? Docker and Symfony are running and other doctrine commands seem to work
docker-composer.yml
version: '3'
services:
###> doctrine/doctrine-bundle ###
database:
image: postgres:${POSTGRES_VERSION:-14}-alpine
environment:
POSTGRES_DB: ${POSTGRES_DB:-app}
# You should definitely change the password in production
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-!ChangeMe!}
POSTGRES_USER: ${POSTGRES_USER:-app}
volumes:
- db-data:/var/lib/postgresql/data:rw
# You may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
# - ./docker/db/data:/var/lib/postgresql/data:rw
###< doctrine/doctrine-bundle ###
volumes:
###> doctrine/doctrine-bundle ###
db-data:
###< doctrine/doctrine-bundle ###
Downloaded the project. Did everything from scratch... same issue
Hey Algirdas,
We're sorry to hear you're having trouble! We'll try to help you solve this issue.
Could you tell me what exactly steps are you following? Did you start from the start/ folder of the downloaded course code? Also, did you follow all the steps from the README.md file in that start/ folder?
Cheers!
Hello Victor,
So I am following from the very first tutorial. Finally 5mins ago I managed to fix it. I am using Ubuntu. My PHP version is 8.1.9
I ran these 2 commands:
sudo apt-get install php8.1-pgsql
and then restarting apache
sudo service apache2 restart
Now I have another issue :D
symfony console doctrine:database:create
I get: An exception occurred in the driver: SQLSTATE[08006] [7] connection to server at "127.0.0.1", port 49153 failed: FATAL: password authentication failed for user "app"
Any ideas how I can fix this? I did not change anything in .env or docker files. So password is still ChangeMe and user is app
Hey Algirdas,
I suppose you need to change those "ChangeMe" credentials to your real credentials to make it work ;)
Cheers!
I'm trying to connect to the database with symfony console doctrine:database:create but the error message I receive is 'SQLSTATE[08006] [7] connection to server at "127.0.0.1", port 5432 failed: Connection refused. Is the server running on that host and accepting TCP/IP connections?'
Thank you, ;)
HI,
Are you using docker? if so are you running it from PHPStorm console?
Cheers!
I'm using Docker and I've tried with Visual Code / PHPStorm and macOs native terminal / iTerm2 and Visual code / PHPStorm terminals and I get the same error.
If I try another postgresql database manager like DBngin (for example) I've no problem configuring the database.
I'm sure I'm missing some step but I don't know what, ;););););)
Hey Carlos-D!
Hmm, let's see :). Ok, so the error is this:
SQLSTATE[08006] [7] connection to server at "127.0.0.1", port 5432 failed: Connection refused
That tells me that Symfony is reading the DATABASE_URL
from your .env
file, as this is the default port used in that file. However, if you're using the Docker setup we've provided, that value should be overridden by a real DATABASE_URL
env var. The process looks like this:
A) You run docker-compose up -d
to start the Docker contain that ships with the code (did you do this step? It seems like the most likely candidate for the problem).
B) Once you do this, whenever you run symfony console ...
, the symfony
binary will detect that you have a Docker container called database
running for postgres. It will then read the connection parameters to that Docker container and expose a real environment variable called DATABASE_URL
that points to it.
C) This means that, when the command actually runs, it will talk to the Postgres instance in your Docker container.
Another way to see if the DATABASE_URL
environment variable is being properly added by the symfony
binary is to run symfony var:export --multiline
to see if you see it in the list. It should look something like DATABASE_URL=postgres://symfony:ChangeMe@127.0.0.1:56986/app?sslmode=disable&charset=utf8
.
Cheers!
the video stops playing due to an error happening at the 2:07 minute mark. Chrome throws an error: "The media playback was aborted due to a corruption problem or because the media used features your browser did not support.", safari will just freeze and seemingly play but both audio and video stop.
Hey Found,
We're sad to hear you're experiencing some problems with playing the video in Safari! What version of the browser do you use? Can you try to upgrade it to the latest? Mine is "Version 15.5 (17613.2.7.1.8)" and I cannot reproduce it, it works great for me. Please, could you try in a different browser, like Google Chrome? Is it the same error and at the same second for you?
Also, here's a little tip: as a temporary workaround you can download the video and watch it locally. I understand it's not perfect but could help in this specific case.
Cheers!
It is on MacOS Monteray 12.5
Safari Version 15.6 (17613.3.9.1.5)
And regarding Chrome, it happens in chrome with the stated error message.
Chrome Version 104.0.5112.79 (Official Build) (x86_64).
It only happens in this video on the mentioned minute mark.
Thanks for the tip ;) will do that.
Cheeers.
Hey Found,
Hm, that's weird that it happens only on the specific video and only at the specific time, and out team still can't reproduce it. It makes me thinks that it might be a temporary Vimeo issue because all our videos are hosted on Vimeo. I hope it will be better soon, but nothing much we can do here. I'd recommend you to download problematic videos and watch them locally.
Sorry for the inconveniences!
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
}
}
You will need psql drivers for PHP, otherwise it will fail with "An exception occurred in the driver: could not find driver"
This will help:
sudo apt-get install php-pgsql