Posts

Showing posts with the label symfony

Installing Packages in Symfony using Flex and Packs

Explanation of installing packages in Symfony using Flex and Packs. Flex Package is a ready-to-use functionality that adds new features to simplify development process. In Symfony, packages are called bundles and are installed via Composer. In order for bundle to work, it needs to be attached to framework. This usually requires doing some extra work - adding a bundle class in config/bundles.php and adding a config file in config/packages/*.yaml and possibly some others. In order for bundle to automatically attach after installation, plugin for Composer called Flex was created. Flex after installing bundle executes recipes, that is instructions for automating attachment and configuration of bundle in Symfony. Executed recipes are written to symfony.lock file. There are two recipe repositories: main and contributor . Main repository contains quality recipes for popular bundles. Contributor repository contains recipes for the rest of bundles developed by community. Bund...

Symfony Commands for Loading and Purging Fixtures

Doctrine already has a command to load fixtures, symfony console doctrine:fixtures:load , but does not take into account the reset of sequences and there is no command just to purge fixtures. The article describes Symfony commands: Purge Database, Restart Sequences (PostgreSQL) and Load Fixtures Purge Database Without Loading Fixtures Purge Database, Restart Sequences (PostgreSQL) and Load Fixtures // src/Command/LoadFixturesCommand.php <?php namespace App\Command; use Doctrine\DBAL\Exception; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\ExceptionInterface; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'app:fixtures:load', description: 'Purg...

Controllers for Resources, Services and Web Pages in a Symfony Application

The controller processes the request and returns a response. Actions for resource controllers, services, and web pages make up the way you interact with application. Resource A resource is an entity that stores data. For example, news, product, order, article, comment. Also, the resource is a list of all units of this entity. Main actions on the resource: Creation (adding to the list) Receiving Editing Removal Resource API example: GET /api/catalog/products/30004 # getting the resource "Product" by identifier "30004" POST /api/blog/articles # creating an "Article" resource with data in the body of the POST request DELETE /api/blog/comments/1250 # delete resource "Comment" with id "1250" The segments catalog and blog in the URLs mean that the resources belong to a specific domain and can be separated into the appropriate bundles. For example, the domain-specific resources of a catalog can be Product , ...

Creational Design Patterns in Symfony Framework

Creational design patterns include: Simple factory, Abstract factory, Factory method, Builder, Prototype, and Singleton. Let's find real examples of using these design patterns in the Symfony framework. Simple factory The Simple Factory pattern creates objects of various classes. <?php namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; class SessionHandlerFactory { public static function createHandler(object|string $connection, array $options = []): AbstractSessionHandler { if ($query = \is_string($connection) ? parse_url($connection) : false) { parse_str($query['query'] ?? '', $query); if (($options['ttl'] ?? null) instanceof \Closure) { $query['ttl'] = $options['ttl']; } } $options = ($query ?: []) + $options; switch (true) { case $connection instanceof \Redis: case $connection instanceof \RedisAr...

What's Difference with Component, Bundle and Bridge in Symfony Framework

Component A component is a part of a system that provides a specific functionality. For example, the HttpFoundation component provides an object-oriented representation of an HTTP request and response, the HttpClient component provides the ability to make HTTP requests to the API, and the Routing component can find the controller by URL. Bridge The bridge integrates an third-party software with Symfony components by providing an add-on for both of them. For example, the twig-bridge adds Symfony component functions to the Twig template, the monolog-bridge provides handlers for sending logs to mail, notification or Elasticsearch, and the doctrine-bridge adds an EntityValueResolver to resolve the Doctrine entity in the controller and the user provider with using the repository. Bundle The bundle integrates an third-party software or new functionality with the framework. For example, DoctrineBundle provides database services, EasyAdminBundle provides an admin panel,...

Handling Exceptions in a Symfony Application

There are two main types of application errors: The request can be processed, but the data is not valid The request could not be processed due to a broken part of the application or system If the requested URL is not found because it is not defined in the API specification, then an HTTP 404 (Not Found) response is returned. The request can be processed, but the data is not valid refers to a server response with an HTTP code 400 (Bad Request) detailing exactly which data sent is invalid. Errors of this kind are foreseen in advance and their handling is a normal part of the application. For example, after submitting the news form data to the server, one of the fields did not pass validation and the server returned an HTTP 400 (Bad Request) response with error details to be shown to the user. This type of error can not be logged, because error details are returned immediately with the server response and no server-side fixes are required. This kind of error displays the sa...

How a Request is Processed in the Symfony Framework

Loading Front Controller It all starts with the execution of the public/index.php file. // public/index.php <?php use App\Kernel; require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; return function (array $context) { return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); }; This file is also called Front Controller . It is automatically generated when a Symfony application is installed and is located in recipes of the FrameworkBundle component. The FrameworkBundle component contains a microkernel trait that loads data from /config/* configuration files, such as services, routes, parameters. It contains a basic set of console commands such as clearing the cache, dumping configurations, services, routes. It also contains the AbstractController base class with useful functions for controllers. The public/index.php file executes the /vendor/autoload_runtime.php file. // vendor/autoload_runtime.php <?php //...

Symfony Application Using Routing

Sample of how to use routing in a Symfony web application. The main meaning of these sample is in the configuration and routing settings, and not in the business logic, so the actions in the controllers have pseudo-code as comments. The API describes features of a product catalog in an online store. List of entities that are used in this API: Category Product Review Entities don't really exist, only controllers and actions are designed. The routing configuration for the controllers: # /config/routes.yaml controllers: resource: ../src/Controller/Catalog type: attribute prefix: '/catalog' name_prefix: 'catalog_' trailing_slash_on_root: false This means that the routes for all controllers in the src/Controller/Catalog directory will be prefixed with /catalog , so this prefix can be omitted in the controllers. The /catalog prefix is needed to separate the catalog section with products from other sections of the site such a...