Posts

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...

How to choose a documentation license

The documentation released under the license allows the author to specify what actions the user is allowed to do. For example, can I copy, distribute, modify and use for commercial purposes? The following are popular licenses developed by the non-profit organization Creative Commons in order from most permissive to most restrictive in terms of user experience. List of licenses with permissions, conditions and prohibitions Attribution 4.0 International (CC BY 4.0) allows you to copy, distribute, modify and use for commercial purposes, provided that the author is credited, a link to the license is added and the changes made are indicated. Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) may be copied, distributed, modified and used for commercial purposes, provided that the author is credited, a link to the license is added, changes made are indicated and following the same license. Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) may be copied, distributed...

How to choose Open Source license

The article deals with popular Open Source licenses: GNU GPLv3 GNU AGPLv3 GNU LGPLv3 Mozilla Public License 2.0 Apache License 2.0 MIT License The Unlicense Before choosing a license, let's first understand what a license is. License is a permission to perform certain actions on a work. Such actions may include the use, distribution, and modification of the work. It is forbidden to perform these actions without an issued license, as the work is protected by copyright.

Как настроить подключение к MS SQL через ODBC?

Image
В этой статье вы узнаете: Что такое ODBC; Как создать имя источника базы данных (DSN, Database Source Name); Как подключаться к ODBC из PHP. Настраивать будем под операционную систему Windows 7 с примерами кода на языке программирования PHP. Для тестирования подключения к MS SQL серверу я создал аккаунт на хостинге gearhost .

Установка xhprof и Graphviz на Windows

Image
В этой статье я расскажу как установить xhprof и Graphviz на Windows , какие ошибки возникают и как их устранить. xhprof — php-расширение от facebook. Это иерархический профайлер, который позволяет собирать такую статистику как время выполнения каждой функции, использование памяти, время ожидания, количество вызовов. Graphviz — пакет утилит по автоматической визуализации графов, заданных в виде описания на языке DOT, а также дополнительных TUI и GUI программ, виджетов и библиотек, используемых при разработке программного обеспечения для визуализации структурированных данных.