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!
¡Hola a todos! ¡Bienvenidos a los 30 días de LAST Stack! Tengo que decir que éste puede que sea mi tutorial favorito. Me lo he pasado en grande construyéndolo, porque a diferencia de lo que suelo hacer por aquí, voy a centrarme un poco menos en enseñar conceptos profundos y más en crear un producto rico, pulido y bonito. Y creo que te va a encantar.
Pero primero, LAST Stack, ¿qué demonios es eso? Es un acrónimo que... Me inventé. Quería algo divertido que encajara con un paradigma totalmente nuevo. Son las siglas de Live Components, AssetMapper, Stimulus y Turbo. Es una pila de front-end que nos permitirá construir una interfaz de usuario realmente rica -como una aplicación de una sola página, con modales y AJAX por todas partes- pero totalmente con Symfony, Twig... y sólo un poco de JavaScript. Ah, y esto no requerirá ningún paso de compilación ni Node.js. ¡Guau!
Al final de este tutorial, vamos a tener patrones reutilizables que podemos aprovechar en nuestros proyectos para hacer las cosas realmente rápido pero que funcionan y sientan increíblemente bien.
El núcleo de todo este sistema es Hotwire: una colección de bibliotecas que incluye Turbo, Stimulus y Strada. Strada es el nuevo chico del barrio y parece genial. No tendremos tiempo de hablar de ella, pero promete permitirte tomar el mismo proyecto que estamos a punto de construir y utilizarlo para impulsar una aplicación móvil. Woh.
Otra cosa genial de Hotwire es que... no es exclusivo de Symfony. Lo utiliza, por ejemplo, la comunidad Ruby on Rails. Y muchas de las cosas que vamos a construir proceden de patrones que aprendí de gente de esa comunidad. El hecho de que todos utilicemos la misma herramienta significa que podemos compartir bibliotecas, compartir ideas y construir sobre los hombros de los demás. Eso es enorme.
Configuración del proyecto
Así que, ¡manos a la obra! Como es divertido hacer cosas bonitas que saltan en la pantalla, deberías descargarte el código del curso y codificar conmigo. Cuando descomprimas el archivo, encontrarás un directorio start/
, que contiene los mismos archivos que ves aquí, ¡incluido el importantísimo README.md! Aquí se explica cómo configurar el proyecto.
El último paso será abrir un terminal, entrar en el proyecto y ejecutar:
symfony serve -d
Para iniciar un servidor web local en ... oh, en mi caso, 127.0.0.1:8001
. Ya debo tener algo funcionando en el puerto 8000. Haré clic en el enlace para ver una página grande y fea de... ¡nada! ¡Eso es a propósito!
Vamos a empezar con un proyecto Symfony 6.4. He preinstalado Twig y tenemos dos entidades diferentes - Planet
y Voyage
- porque vamos a construir un sitio de planificación de viajes para extraterrestres. También tengo algunos data fixtures y he utilizado MakerBundle para generar un CRUD para cada entidad. Este PlanetController
,VoyageController
y estas plantillas proceden de MakerBundle, con sólo unos pocos ajustes de estilo.
Pero básicamente... ¡no pasa nada especial! Tenemos un MainController
, que alimenta esta página de inicio:
Show Lines
|
// ... lines 1 - 12 |
class MainController extends AbstractController | |
{ | |
#[Route('/', name: 'app_homepage')] | |
public function homepage( | |
VoyageRepository $voyageRepository, | |
PlanetRepository $planetRepository, | |
#[MapQueryParameter('query')] string $query = null, | |
#[MapQueryParameter('planets', \FILTER_VALIDATE_INT)] array $searchPlanets = [], | |
): Response | |
{ | |
$voyages = $voyageRepository->findBySearch($query, $searchPlanets); | |
return $this->render('main/homepage.html.twig', [ | |
'voyages' => $voyages, | |
'planets' => $planetRepository->findAll(), | |
'searchPlanets' => $searchPlanets, | |
]); | |
} | |
} |
Contiene una consulta que nos ayudará más adelante... pero la plantilla, ahora mismo, está haciendo un montón de nada:
{% extends 'base.html.twig' %} | |
{% block title %}Space Inviters!{% endblock %} | |
{% block body %} | |
<h1>Space Inviters: Plan your voyage and come in peace!</h1> | |
{% endblock %} |
Sin CSS, sin JavaScript, sin activos de ningún tipo... y el sitio no hace nada. Pero en 30 breves lecciones, transformaremos esto en una pequeña obra maestra digital.
Eso es todo por el día 1. Mañana instalaremos AssetMapper: un sistema para manejar CSS, JavaScript y otros activos del frontend con pilas incluidas... pero sin ningún paso de compilación.
23 Comments
Cool! Thank you for sharing it @Adn-B
Hello guys, I'd like just to post here so it might help. I followed to readme but I had error trying to connect with the database. As Ryan posted in other comments execute symfony var:export --multiline
to check if DATABASE vars are exported and they werent.
I'm running Windows 10 with Composer setup installed and Wamp with php versions 7.x and 8.x. I was able to solve the problem uninstalling composer. It seems as some how the default php version defined when installing composer was messingup symfony cli.
See ya, and keep up the good work.
Thanks for the hint @donwilson. I'm running Mac Sonoma on an M1 pro and had the same problem (missing DATABASE vars). For me the problem wasn't composer conflicting with the Symfony binary it was that in this project (and I believe newer docker compose projects) the compose file is named 'compose.yaml' and I think Symfony CLI hasn't caught up yet because once I changed this to docker-compose.yaml and reserved the app using 'symfony serve' the DATABASE vars were exported and everything works as expected. I hope this helps someone else on a Mac if they have this problem.
Nice catch !! I haven't noticed that change.. Thanks for adding up !
Hey @skofield!
Ah, that makes sense! The project DOES come with the newer compose.yaml
file (formerly docker-compose.yaml
. The latest symfony
binary does support this, but it was added only in a recent version - it was in version 5.6.2 released in late October 2023.
This will probably trip up a few people - so I'm happy to have the conversation here!
Cheers!
Yes!.. with all the tooling one has to handle per project is easy to forget to check if everything is up to date, not to mention to stay up date with all the changes.
Thanks @weaverryan.
Hey @donwilson!
Thanks for posting the steps that unlocked you! And if anyone else has problems with the database connection, you can always go into .env
and change the DATABASE_URL
to use sqlite. It's not as fancy as Postgres, but sqlite is great and will work awesome for the tutorial :).
Cheers!
You are welcome Ryan.
Oh! That's a golden tip there, especially for newcomers. Maybe that line can be included in the Readme file?. I think it might be helpful.
Best regards.
Good idea - let me check into that :)
Hi All,
PROB
I have an issue. Symfony is no longer loading my Docker variables.
I often run a "docker-compose up -d" followed by a "symfony server -d", and everything goes well on other courses, but this one is getting stuck.
**SOLUTION*
- *Rename compose.yaml ===> docker-compose.yaml
- Enabled some extenions in php.ini and it's works
Best,
Amine
Hey @Amine!
This might also be fixed by upgrading your symfony
binary. The Docker world is moving from docker-compose.yaml
to compose.yaml
(hence the change in your Symfony apps), but the symfony
binary needed to be updated for this change... which I know happened... and I think it was only in a couple of months ago.
Anyway, I hope that helps - that's my guess why your Docker variables suddenly vanished!
Cheers!
Hello,
When I try symfony console doctrine:database:create --if-not-exists
I have this error:
In ExceptionConverter.php line 87:
An exception occurred in the driver: could not find driver
I opened php.ini remove the comment to install msql extension, tried to comment
DATABASE_URL="postgresql://app:!ChangeMe!@127.0.0.1:5432/app?serverVersion=15&charset=utf8"
DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=8.0.32&charset=utf8mb4"
but nothing changes...
I fixed the bug by uncomment extension=pdo_mysql
and extension=pdo_pgsql
in php.ini
.
Hey Alison,
I'm happy to hear you were able to fix this issue yourself! Yes, you need that PHP extension because we're using Doctrine in this project which stores data in the MySQL DB.
Btw, you only need to leave one DATABASE_URL uncommented in your .env file. If you leave both - the 2nd will always overwrite the 1st one, and it just mislead :)
Cheers!
Hi there,
I have an issue to boot the database container with Docker, I followed the Readme.md file but I encounter an error when running symfony console doctrine:database:create
. I receive the following error message:
Could not create database "app" for connection named default
An exception occurred in the driver: SQLSTATE[08006] [7] could not translate host name "database" to address: nodename nor servname provided, or not known``
here's my .env file content:
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=8650ba188bbf625cfea2df9a79ae6d61
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
DATABASE_URL="postgresql://app:!ChangeMe!@database:5432/app?serverVersion=15&charset=utf8"
###< doctrine/doctrine-bundle ###
I'm using macOS Big Sur and Docker Desktop 24.0.6
The command composer compose -d
already created the database for me, if you skip symfony console doctrine:database:create --if-not-exists
and execute symfony console doctrine:schema:create
and symfony console doctrine:fixtures:load
you should be able to run symfony serve without any problem.
Hey Alison,
Thanks for this hint! One note: I suppose you meant docker compose -d
instead of composer compose -d
in the beginning? :)
Also, instead of symfony console doctrine:schema:create
it might be better to run symfony console doctrine:schema:update --force
that will apply the difference only if schema is already partially exits but not compete.
Cheers!
Hey @Padawan
That's a bit odd. I believe there's something wrong in your database service config in your docker-compose.yml
file. I'd start by double-checking that it is well configured
Cheers!
Hi @MolloKhan,
The problem was not related to my config files but to Docker-Desktop itself. Here is the solution
Thanks for posting that! I've highlighted your comment in case it helps others. I wish we knew why a small number of users have such a problem with the Docker setup. After all... that's kind of the point of Docker: to "just work" :p.
Sorry for the unrelated comment, but where can I find this great PHPStorm theme?
Hey PapyDanone,
It's Dark theme (Darkula in legacy PhpStorm) - you can change it in the PhpStorm preferences, search for "theme" there. But also a few extra plugins like "Atom Material Design" and "Rainbow Brackets".
Cheers!
"Houston: no signs of life"
Start the conversation!
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": ">=8.2",
"ext-ctype": "*",
"ext-iconv": "*",
"babdev/pagerfanta-bundle": "4.x-dev", // 4.x-dev
"doctrine/doctrine-bundle": "^2.10", // 2.12.x-dev
"doctrine/doctrine-migrations-bundle": "^3.2", // 3.4.x-dev
"doctrine/orm": "^2.16", // 2.18.x-dev
"knplabs/knp-time-bundle": "dev-main", // dev-main
"pagerfanta/doctrine-orm-adapter": "4.x-dev", // 4.x-dev
"pagerfanta/twig": "4.x-dev", // 4.x-dev
"symfony/asset": "6.4.*", // 6.4.x-dev
"symfony/asset-mapper": "6.4.*", // 6.4.x-dev
"symfony/console": "6.4.x-dev", // 6.4.x-dev
"symfony/dotenv": "6.4.x-dev", // 6.4.x-dev
"symfony/flex": "^2", // 2.x-dev
"symfony/form": "6.4.x-dev", // 6.4.x-dev
"symfony/framework-bundle": "6.4.x-dev", // 6.4.x-dev
"symfony/monolog-bundle": "^3.0", // dev-master
"symfony/runtime": "6.4.x-dev", // 6.4.x-dev
"symfony/security-csrf": "6.4.x-dev", // 6.4.x-dev
"symfony/stimulus-bundle": "2.x-dev", // 2.x-dev
"symfony/twig-bundle": "6.4.x-dev", // 6.4.x-dev
"symfony/ux-autocomplete": "2.x-dev", // 2.x-dev
"symfony/ux-live-component": "2.x-dev", // 2.x-dev
"symfony/ux-turbo": "2.x-dev", // 2.x-dev
"symfony/ux-twig-component": "2.x-dev", // 2.x-dev
"symfony/validator": "6.4.x-dev", // 6.4.x-dev
"symfony/web-link": "6.4.*", // 6.4.x-dev
"symfony/yaml": "6.4.x-dev", // 6.4.x-dev
"symfonycasts/dynamic-forms": "dev-main", // dev-main
"symfonycasts/tailwind-bundle": "dev-main", // dev-main
"tales-from-a-dev/flowbite-bundle": "dev-main", // dev-main
"twig/extra-bundle": "^2.12|^3.0", // 3.x-dev
"twig/twig": "^2.12|^3.0" // 3.x-dev
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.4", // 3.6.x-dev
"phpunit/phpunit": "^9.5", // 9.6.x-dev
"symfony/browser-kit": "6.4.*", // 6.4.x-dev
"symfony/css-selector": "6.4.*", // 6.4.x-dev
"symfony/debug-bundle": "6.4.x-dev", // 6.4.x-dev
"symfony/maker-bundle": "^1.51", // dev-main
"symfony/panther": "^2.1", // v2.1.1
"symfony/phpunit-bridge": "7.1.x-dev", // 7.1.x-dev
"symfony/stopwatch": "6.4.x-dev", // 6.4.x-dev
"symfony/web-profiler-bundle": "6.4.x-dev", // 6.4.x-dev
"zenstruck/browser": "1.x-dev", // 1.x-dev
"zenstruck/foundry": "^1.36" // 1.x-dev
}
}
Hey !
If you want to connect to your database with PHPStorm (or other things), update your
compose.override.yaml
file and replace :with :
I hope this helps !