Bienvenue dans le meilleur cours de Symfony (y compris les versions 4 et 5) – le formidable framework PHP !
Dans ce cours, vous apprendrez Symfony du niveau de base au niveau avancé !
À la fin de ce cours, vous serez capable de créer à la fois des sites Web simples et des applications Web dynamiques complexes dans l’excellent framework Symfony PHP.
Cours très pratique ! Presque toutes les sections/concepts sont expliqués à l’aide d’applications/scénarios réels. Dans ce cours, nous allons créer une énorme application de la vie réelle (vous ne trouverez probablement pas de cours où une application plus avancée et nbsp ; comme dans ce cours)
Ceci est un guide très complet sur Symfony, qui est l’un des frameworks PHP les plus populaires. La version Symfony 4 a introduit une nouvelle approche des frameworks php – elle commence petit comme un microframework et se développe au fur et à mesure que vous avez besoin de nouvelles fonctionnalités. Vous les installez à l’aide de l’incroyable outil Symfony Flex. Par exemple, si vous créez un site Web simple et que vous n’avez pas besoin d’une fonctionnalité de connexion, aucun code n’est responsable de la connexion au répertoire du framework. Grâce à cela, notre application ne contient que ce dont nous avons vraiment besoin.
;
************************************************ **
Le cours se compose de trois parties principales :
1. La partie théorique où j’aborde les concepts de base de Symfony sur des exemples avec des effets sur un navigateur web
2. Dans la deuxième partie, nous allons construire une application simple dans Symfony – une liste de tâches à effectuer (base de données utilisée)
3. Dans la partie 3, nous allons créer une application Web avancée pour l’abonnement vidéo dans laquelle nous intégrons PayPal pour les paiements, les catégories de vidéos imbriquées à plusieurs niveaux, la communication avec l’API Vimeo, le déploiement sur le serveur Heroku
ainsi que :
Ajout de la section
BONUS (octobre 2019) : principes de base du composant Symfony Messenger, courtier de messages RabbitMQ et CQRS modèle (Command Query Responsibility Segregation) avec un exemple pratique en simulant un système de commerce électronique composé d’une application principale et de microservices coopérants.
Mise à jour du cours : (janvier 2020) nouvelle section ajoutée API REST avec Symfony & ; Plate-forme API
************************************************ **
Pendant le cours, nous couvrirons de nombreux concepts Symfony simples et avancés tels que : le routage, les contrôleurs, les vues, la base de données avec doctrine orm, les entités et les relations entre elles : un à un, un à plusieurs et plusieurs à plusieurs ; événements & auditeurs, sujets de sécurité tels que la connexion, l’enregistrement, l’autorisation ; également les tests unitaires et fonctionnels, l’injection de dépendances, le conteneur de services, les services symfony, l’héritage de table de doctrine avec des requêtes de base de données polymorphes, l’API REST et bien d’autres.
Ce cours est une combinaison de théorie et d’approche d’apprentissage basée sur des projets. Apprendre en créant de vrais projets est le meilleur moyen d’apprendre les langages de programmation et les outils comme les frameworks PHP.
Toutes les applications du cours ont été réalisées avec Symfony 4 (à l’exception des applications pour la section rest api – Symfony 5). La section Mise à niveau vers Symfony 5 a été ajoutée au cours. Selon la norme Symfony, il n’y a pas de nouvelles fonctionnalités dans Symfony 5.0 par rapport à Symfony 4.4.
N’oubliez pas que seule la pratique rend parfait. Si nécessaire, étudiez le cours deux fois ou plus. Prenez des notes pendant le cours comme un vrai étudiant. Utilisez les documentations, la recherche Google. Enfin, essayez d’écrire l’application vous-même, pas nécessairement la même que dans le cours, vous pouvez essayer de changer, d’ajouter quelque chose, etc. Aucun cours ne fera de vous un très bon développeur web. Cela ne peut que vous rapprocher de cet objectif. Plus on pratique, mieux c’est.
———————————————————
CQ
Question :
Vous avez utilisé Symfony 4 et Symfony 5 dans ce cours pour créer des applications pour mettre en pratique vos connaissances. Pourquoi ne pas utiliser uniquement la dernière version ? Cela signifie-t-il que ce cours est obsolète et que je n’en profiterai pas ?
Réponse :
Absolument pas ! Dans des outils comme les frameworks PHP, les fondamentaux et la syntaxe de base ne changent presque jamais, quelle que soit la version. Mais bien sûr, tout logiciel maintenu évolue tout le temps. C’est pourquoi je vous suggère toujours d’utiliser la version du logiciel que l’instructeur utilise dans le cours. Il évite les erreurs et les confusions. En tant que personne qui souhaite apprendre le développement Web, vous devez savoir que le véritable développement Web implique également d’adapter le code aux nouvelles versions si nécessaire – mais ce n’est pas toujours nécessaire, toutes les entreprises ne le font pas. Le logiciel change si souvent que les instructeurs ne seraient pas en mesure de créer les cours pour qu’ils correspondent à la dernière version. Ce n’est même pas conseillé, car en tant qu’étudiant, vous perdriez un aspect important du véritable développement Web – la conscience que tout change et que vous devez être capable de le gérer.
———————————————
Inscrivez-vous maintenant et commençons à apprendre Symfony !
Il n’y a aucun risque ! Garantie de remboursement de 30 jours
Introduction
What this course is all about, what you will learn, how this course is structured, who I am
What is Symfony, what it is used for, documentation, release process
What you will need to accomplish the course (tools & requirements for students)
Learn how to get the most out of this course
You will get familiar with the applications that we will build in this course
My approach to coding standards and Symfony best practices
Symfony 4 & 5 basics, installation & configuration
Install Symfony 4, check system requirements, take a look at the folder structure
Main Symfony config file and config folder explained
Using Symfony Flex to automate installation of packages. Installing Twig and Doctrine
Request lifecycle in Symfony
Theory - Symfony 4 & 5 core features
In order to go through this section with ease, install the Symfony app using the version in which an app was created. Later I will show you how to upgrade to the latest stable version of Symfony.
You will know two ways of creating routes in Symfony
Basics about Symfony controllers
Symfony views basics
Create database and use it with entities in Symfony
Service container, autowiring of services
Using external service in our own service
Examples of advanced routes in Symfony, optional parameters
Using session flash messages in controllers and views
Using cookies in Symfony (how to get cookie value - see the next lecture)
Using session in Symfony
Using POST and GET data in Symfony. Using Request object
Make custom error pages in Symfony
Handle exceptions in Symfony with example of NotFoundException
How to bind a service to a controller so that it can be accessed via php variable in the controller
How to redirect with dynamic parameters, how to download files, how to forward to another controller
Explore built-in features in Twig: tags, filters, functions, tests, operators
Generate url's for routes and images, escape js, html, css
Make variables global in all Symfony Twig views
Manage css and js files/libraries with Webpack Encore & npm
How to access the User, Request, Session and more in Twig via the app variable
How to render controller results in Twig files
Create a new user and many users using fixtures. Console commands for resetting entire database
Select users from database. Make use of repository
Update a user
Delete a user from the database
Make raw database queries with Doctrine
Use param converter in Symfony to automatically fetch specific object from the database
Execute entity code automatically using Doctrine events
One-to-many relationship in Doctrine. Owning and inverse side of a relationship. Bidirectional & unidirectional types of relations. Proxy classes & lazy loading
cascade={"remove"} vs onDelete="CASCADE" vs orphanRemoval=true deleting options
A user has one address and address belongs to only one user
How to implement Twitter-like follow user feature in Doctrine
Fetch all related objects with one Doctrine query
How to design database when entities share common fields
Create example entities and abstract entity that stores shared properties
Make polymorhpic queries with lazy and egaer loading options. Single and joined inheritance types
Inject parameters to services
Inject other services to a service using constructor injection & service arguments (most common)
Autowire, autoconfigure and public configuration options
Inject optional dependency to a service using setter method
Inject dependency to a service using class property
How to make a service lazy so that it is instantiated only if we call it
How to use aliases for our services names
How to add tags to a service so that it is treated by Symfony in a special way
Two services that implement one interface. How to deal with this in our application. Import configuration file to another
List all of services that you can autowire & all services from the Symfony container
Basic usage of cache in Symfony. Set cache expiration time
Use cache tags to store/clear related items in/from cache
Using Symfony console to automate tasks & get helped
Use profiler tool in Symfony. Take a look at the error stack trace
Difference between environments and kernels
Deploy your Symfony application to live server
Events & Listeners base concepts in Symfony. List all of Symfony events. Built in Symfony events
Create listener that listens to the kernel response built in Symfony event
Create an event and dispatch it
Create subscriber and subscribe to custom event & dispatch it
One subscriber can listen to many events
Set priorities of subscribed events
Update video entity and create form class for it
Render the form in view file
Style your symfony form in easy way
Send form and save data in the database
Validate a form before saving data (backend side validation)
Use form events to dynamically modify/build forms
Use "mapped false" option in forms
How to upload files in Symfony application
Install email package & send emails in Symfony
How to delay the delivery of emails to make loading website faster (send emails using server cron job)
How to test that an email was sent
Create special user for security purposes such as register, login, etc.
Register a new user
Login to the application
Logout from the application
How to implement 'remember me' feature in the login form
Using csrf token to protect html forms from being hacked
Install security checker package and check security
Use annotations in controllers to authorize user actions
Use access control feature in configuration file to restrict access to pages
Use denyAccessUnlessGranted method to make authorization in controller method
How to authorize user action in Twig view files
How to use voters to authorize user actions
Install a package for unit testing, command for running all tests
Make first unit test in Symfony and test simple calculator service
Install a package for functional testing, make first functional test
The most common used assertions while testing
How to click links on the website in functional tests
How to send forms in functional tests
Use data providers in functional tests to make test methods simplified
Isolate your tests using second database connection or transactions
How to create mocked (fake) objects in testing
Generate code coverage report during testing
Install and configure a package for translations in Symfony application
Make translations in view files
How to translate in controllers
How to translate routes
How to pluralize translated strings
First application in Symfony: to-do list app (CRUD)
In order to go through this section with ease, install the Symfony app using the version in which an app was created. Later I will show you how to upgrade to the latest stable version of Symfony.
We will use composer to install Symfony 4 and xampp to work with the framework. We will also make nice url for our application by using virtual hosts in xampp
We will display our template directly in the Symfony by moving template to it, creating first controller and route
In this lecture we will create controller methods for 3 actions in our app and use path() function in views to create links to those routes
We will make connection with the database and create first entity in Symfony 4 to communicate with the database
We will fetch all the records from the database using Doctrine and display it on the website
Create method for switching a status of the task: done or undone
Create the method for deleting a task using Doctrine ORM
Controllers, routes, views - install and move html template to Symfony (App)
In order to go through this section with ease, install the Symfony app using the version in which an app was created. Later I will show you how to upgrade to the latest stable version of Symfony.
Installation of Symfony 4 framework and all the necessary libraries. First steps with moving template to Symfony, installing Twig template engine, extending base layout. Create first route, controller and first page
Moving admin area pages to Symfony. Use asset() function. Create first twig blocks in views
Create routes and controller methods for pages and link them with path() function
Create routes and controller methods for pages and link them with path() function
Make base Twig layout for admin area. Create routes and controller methods for pages and link them with path() function
Create routes and controller methods for pages and link them with path() function
Use twig "for" loop etc
Install & use Webpack-Encore for handling our assets
Doctrine entities, relations, fixtures,console commands - video categories (App)
Create Category & Video entities. Make first database relations on entities. Create fixtures for Category entity (fake data). Use console commands for handling database related stuff
Create subcategories for fixtures
Finish creating fixtures for Category entity
Use Symfony render controller feature. Create advanced route. Use twig filter. Use Doctrine to fetch all main categories (with parent column equals to null)
Create custom Twig filter to slugify url (e.g. change "Romantic Drama" to romantic-drama)
Create main abstract class for categories and child class for front-end. Install composer packages for debugging code
Create method for building tree array for categories
Build and display nested html li element for front-page categories. Use "raw" Twig tag
Find main parent of categories, use Twig filters, refactoring of our code
Build html for categories in admin area (html ul li). Update Category entity to allow for deleting a category. Controller method for deleting category
Build html for categories in admin area (html option list). Use php recursive method. Render controller result in Twig file
Controller method for editing category, render controller in view
Create html form in Symfony. Modify controller method to handle POST requests. Build html form in view with Symfony approach. Form validation
Validate form
Save category in database. Unique key for name field in category table
Code refactoring
First unit tests, mocking classes (Symfony App)
Unit test slugger for url's. Sh script to automate tasks
Mocking category class
Build 3 mocked classes: two for admin area and one for front-end
Testing admin option list (html)
Testing admin "ul li" list (html)
First functional tests with isolation (Symfony App)
Installing necessary dependencies. Create first functional test
Configure database transactions (testing with isolation)
Test editing category
Test deleting category
Paginate, sort and search - videos on the website and test it (Symfony App)
Create video fixtures (fake video data to display on website)
Display videos on front-page taken from the database
Paginate list of videos
Build recursive function to get id's of child categories and display videos from them
Sort videos by title using Doctrine Query Builder
Search videos by title in the database and display them
Test no results on the website
Test results were found on the website
Test sorting
Login and authorization system, sample user data - fixtures (Symfony App)
Make user entity. Install security package with Symfony Flex
Make user fixtures (example user data in the database)
Make changes in configuration file for login functionality
Modify controller methods and views
Display roles restricted stuff and data of currently logged in user
Prevent access user to content based on user roles
Prevent access user to content based on user roles - part 2
Display links for users depending on login status
Display links for users depending on login status
Securing access to superadmin pages
Install package for checking security of our application
Html forms, register new users (Symfony App)
Build html form element for User entity
Create register controller method and html form
Encode user password and login user automatically after registration
Other functional tests (Symfony App)
Test delete and edit category
Test categories. Change login method for testing purposes to http_basic
Test access to secured url's
Test access to secured url's
Doctrine and LifecycleCallbacks, repositories - comments on videos (Symfony App)
Create Comment entity, enable LifecycleCallbacks
Create comment fixtures (fakes data) and implement dependent fixtures interface (first user data must load and then comment fixtures)
Display dynamic value of number of comments and video placeholder for not logged in users
Controller method for displaying video details. Using repository and doctrine query builder to load video with dependent entities
Display comment details, install knp-time-bundle
Create controller method and html form
Code refactoring. Install package for testing with isolation using database rollback feature
Test add new comment
Many-to-many Doctrine relation - likes/dislikes functionality (Symfony App)
Create video entity and many-to-many relations (like functionality)
Create fixtures for videos including like and dislikes of videos
Prepare for likes/dislikes functionality on the website
Prepare javascript for likes, compile it with Webpack encore
Prepare controller method
Prepare controller method for like and dislike
Sort by likes using Doctrine query builder
Sort by likes using Doctrine query builder
Improve searching
List videos in admin panel depending on who is logged in - an administrator or a regular user
Create two php traits for testing purposes (role admin and role user traits)
Test like video
Test dislike video
Testing proper number of likes
Move likes code from frontcontroller to trait and login code to new controller
Create new controllers for admin area and move code to them
Doctrine database relations & Redis for session - video subscriptions (App)
Make Subscription entity and relate it with User entity
Make subscription fixtures
Update admin profile - show cancel plan link to a regular user
Display a video placeholder for users that do not have valid subscription
Create dynamic values for plan names instead of hardcoding it. Create new controller for subscriptions
Install and configure Redis as service (for session storage)
Register new users with choosing video subscription plan (Symfony App)
Register with proper subscription plan
Register with proper subscription plan
Create php code responsible for saving subscription to registered user
Register users using saveSubscriptionPlan trait
Enable cascade deletion of videos and comments that belong to deleted user
Functional testing of subscription
Flash messages, update user profile using Doctrine (Symfony App)
Delete admin profile
Build Symfony html form and update admin profile
Add vimeoapikey html field to superadmin profile
Use Symfony flash messages to show errors when form data are invalid
Save user data using Doctrine. Encode user password
Test if a user can delete his account and change password
Superadmin can display and delete all users
Test if superadmin can delete users
Upload files - two implementations of uploader interface (Symfony App)
Create a form for uploading videos locally and test access to uploading route
Create uploader interface and uploader class for local uploading. Configure uploader service
Create global variable to differentiate route name depending on environment
Superadmin can delete videos
Code refactoring and display categories select list in admin panel. Update video category
Change video for no members
Remove novalidate attribute from html forms
Create uploader service, controller method. Configure uploader service
Set duration for uploaded video to Vimeo video service (by authenticated ajax call to Vimeo API)
Delete a comment and secure this by authorization (a user is allowed to delete only his own comment)
Events & listeners, sending emails (Symfony App)
Create listener that listens to the adding new video event
Send email when adding new video, email spooling
Test admin can delete a video
Translations to other languages (Symfony App)
Translate website to other languages, update route names
Translate text in view files, functional tests
Caching pages, services & event subscribers (Symfony App)
Install cache package, implement two cache services and configure it in Symfony
Cache video list on the website
Clear cache before and after each functional test
Clear cache after admin changes data on the website (by creating event subscriber)
Cache functional testing
Different enviromnents - Heroku deployment (Symfony App)
Files caching mechanism do not work on Heroku free account, so we need to customize our code to prevent some unexpected behavior.
Prepare for Heroku deployment, create configuration files, update composer.json file, create database
Deploy video subscription application on Heroku
Symfony services by PayPal integration (Symfony App)
Be aware of constantly changing PayPal look and feel
Create PayPal service and subscription buttons
Handle paypal verify url
REST API with Symfony & API Platform
What we will learn and build in this section of the Symfony course
EasyAdmin bundle will alternatively serve as an admin component for our API Platform app. Using EasyAdmin bundle you can create an admin panel for your Symfony application in a minute!
Use schema.org service to create entities with property names recognizable by most popular search engines
Enable editing entities through EasyAdmin
Install a package for uploading images through EasyAdmin bundle
Update Product and Offer entities. One to many relation on entities
Generate scafoold files for security purposes with just one console command. Ok, we have just created a backend for saving data to be consumed by our API
We will build client app to consume api using pure JavaScript
With API Platform creating pagination links is a breeze
Create a simple router to manage different routes in our js app
We will sort list of products by name
Show only those products who have images
Make api call to find products by its name
Allow to fetch related objects (offers for a product) together with parent object
Check if our json-ld results are recognizable by Google search engine
The first api consumer app was just a frontend. Now let's create backend consumer api app
Add an offer to the product using API Platform POST request
Delete an offer from the product using API Platform DELETE request ("item operation")
Enable token based authentication and authorization to our API Platform application
Make POST api call to register a new user
Login by getting and sending JWT token to backend. Test if token is valid with Postman
Authorize users to delete only his offer
Save user data for his offer using event subscriber
Prepare for fetching only offers belonging to logged in user using API Platform subresource feature
We will need user id to get only his offers
Call sending JWT token header only in one place
Handle token expired, incorrect or missing
If JWT token is not correct and we want to make login protected actions, send token automatically. Use JavaScript Promises
Create LostPassword Symfony entity
Prepare LostPassword entity to be valid as a API Platform resource, "colletion operations". Create controller to handle request for new password
Use POST api request to send the token to the user that wants to change his password
Create ResetPasswordRequestEvent event and dispatch (fire) it when sending reset password request
Create ResetPasswordRequestListener listener to send email for changing the user's password
Custom API Platform operation - prepare final request to change user's password (modify User entity and create a controller to handle the operation)
PATCH API Platform request - update users table with a new password. Patch request updates a record (like PUT request), but only specific columns choosen. PUT request replaces entire record
Create JavaScript class to handle REST API file upload
Create UploadFileController as the backend handler for uploading files
Make final post api request to upload a file
Using validation groups on operations. Convert Symfony PHP exceptions to HTTP errors
Write and run functional tests for your API
Getting offers is allowed only by users logged in to the application
Use Symfony Reverse Proxy built-in feature and http headers to cache rest api results
Deploy our three apps to Heroku: API Platform app, client frontend app and client backend app
While testing our apps we can see some errors. Fix them!
Make sure you thoroughly tested your API Platform app before exposing it to production!
BONUS section: RabbitMQ & CQRS with Symfony Messenger
In order to go through this section with ease, install the Symfony app using the version in which an app was created. Later I will show you how to upgrade to the latest stable version of Symfony.
What we can do with Symfony Messenger Component
What is RabbitMQ, what it is used for. RabbitMQ Exchange types
Command Query Responsibility Segregation pattern - when it is useful
Mix Symfony Messenger, RabbitMQ, CQRS together and build something amazing!
Install first Symfony app: e-shop website (simulation)
Inside a controller make three basic requests that we want to simulate in our messaging system
Install Symfony Messenger Component, configure it. Use component to dispatch query message
Create command message for ordering shop products and dispatch it via message bus
Create command message for signing up to sms service and dispatch it via message bus
Route SignUpSMS and Order messages to Doctrine transport - make processes asynchronous. Consume the messages
RabbitMQ installation on Linux Ubuntu
We will send OrderProducts message to warehouse database service using Fanout Exchange of RabbitMQ. Make use of Worker
We will send OrderProducts message to email service using Fanout Exchange of RabbitMQ. Make use of Worker
We will send Sms message to sms service using Direct Exchange of RabbitMQ. Make use of Worker
What you need to remember about if you plan to deploy your Messenger app to production and expose it to clients