Symfony2 application framework overview
When developing web applications, almost always we want to start with some kind of ready-made database and fasten the necessary functionality with convenience for the developer. Especially for a novice developer it is useful to watch finished projects. Frameworks, in particular Symfony2, provide a lot of tools to make application development enjoyable. But among many bundles (modules of Symfony2 applications) it can be difficult to understand which set is worth choosing.
Each company that has some experience in developing on Symfony2 most likely has its own minimal framework for starting, but in this article we will look at the options that are in the public domain.
This article is for readers who are just new to Symfony2. And people who actively use this framework, I ask you to share comments.
We will describe each demo in the following format:
Symfony2 is an application provided by the Symfony2 community as an example application. In order for the development to be comfortable and fast, in any case, you will need to search and add more bundles (depending on the goal being pursued). The framework is suitable for familiarization with the core of the framework, the structure of the application.
An AppBundle has been created where you can start working (although the bundle structure is easy to generate using php ./app/console generate: bundle). Twig is used as a template engine (can be replaced by another). Used by Doctrine ORM / DBAL and Doctrine PHPCR-ODM, configured by Swiftmailer, annotations included.
Not detected.
The purpose of the assembly is to make it easier for the developer to add CMS functionality to the application. Key principles for existing bundles: scalability, usability, good documentation, and good test coverage. The idea of a loosely coupled CMS (decoupling CMS decoupledcms.org ) is being implemented .
A detailed discussion can be found at the link “Symfony CMF. Part 2 and the last " by waitekk .
Not detected.
Step-by-step construction is presented in the tutorial .
Building a REST API is not easy. This paragraph provides an example application with a built REST API.
A blog api example has been implemented. The query processor and its interface are placed in separate classes, the model is presented as an interface of getters and setters implemented by the Page entity. Separating class responsibilities allows you to write better code.
To configure security, an additional layer is required, for example, a bundle that allows you to use Oauth2 ( HWIOAuthBundle ).
The LINK / UNLINK implementation is difficult to remember.
The PATCH method can be varied ( some recommendations ).
In addition to the base in the form of Symfony Standard Edition
Not detected.
Application framework prepared and used by Evercode.
One of the features is the configured deployment configuration file (capifony) and there are HipChat connection settings for notifying the deployment status and sending critical error logs.
[ Source ]
When using capifony, you may need to tweak it:
To demonstrate the work of the sonata project bundles , such a web application was created - a store with rich functionality.
It can greatly simplify the solution of many typical tasks (page layout, creating the admin panel and other CMS functionality, managing media files, etc.), but it requires significant time for familiarization, because the documentation could be better.
A large number of bundles, and many of them are auxiliary (dependencies), so I give only the most interesting in terms of creating the ultimate functionality.
There are no particular difficulties, the application is maintained in a healthy state.
The bundle significantly reduces the amount of code required to perform standard tasks (sending mail, flash messages, auto-registration of services, creating forms). There is also an assistant for creating missing view templates, if the template was not found, then it can be created right away in the browser directly on the form on the error page.
Among the shortcomings is a small community and the need for additional study.
In addition, SensioGeneratorBundle copes well with the generation of Bundle, Controller, CRUD, Entity, FormType. And its use is more understandable than hiding this code with KnpRadBundle.
[ Wiki project ]
No problem.
Based on Symfony SE , a simple blog is created. Following the link to the source there is a step-by-step description of the creation process, but it is better to focus on the Sonata sandbox , in which a small blog is also implemented. Better in the sense that the Sonata project is constantly updating the demo.
[ Source ]
Only used by Symfony SE .
This lesson has been using the old version of Symfony2 (2.0.3) for several years. Not even used composer.
Each company that has some experience in developing on Symfony2 most likely has its own minimal framework for starting, but in this article we will look at the options that are in the public domain.
This article is for readers who are just new to Symfony2. And people who actively use this framework, I ask you to share comments.
We will describe each demo in the following format:
- Title
- Description
- Installation
- Basic bundles
- Scan Difficulties Encountered
Content
- Symfony standard edition
- Symfony content management framework
- REST API
- Evercodelab skeleton
- Sonata sandbox
- Knp rad project
- Symfony2 blog
Symfony standard edition
Description
Symfony2 is an application provided by the Symfony2 community as an example application. In order for the development to be comfortable and fast, in any case, you will need to search and add more bundles (depending on the goal being pursued). The framework is suitable for familiarization with the core of the framework, the structure of the application.
An AppBundle has been created where you can start working (although the bundle structure is easy to generate using php ./app/console generate: bundle). Twig is used as a template engine (can be replaced by another). Used by Doctrine ORM / DBAL and Doctrine PHPCR-ODM, configured by Swiftmailer, annotations included.
Installation
Composer | composer create-project symfony / framework-standard-edition my_project_name |
---|---|
Symfony | symfony new my_project_name |
Basic bundles
Table with names and a brief description
Frameworkbundle | the foundation |
---|---|
SensioFrameworkExtraBundle | adds a few annotations that can significantly simplify the controllers, to the point that all the logic of the controller will be recorded in the annotations. |
Doctrinebundle | doctrine dbal & orm support |
Twigbundle | support for the template engine and some extensions |
Security bundle | General principles of operation are chewed by pluseg in the Symfony2 \ SecurityBundle article |
Assetic bundle | control js, css, pictures, icons |
SensioGeneratorBundle | adds commands to generate code |
WebProfilerBundle | debug panel in development and testing environments |
SensioDistributionBundle | composer hooks, web configurator, security checker. Used in development and testing environments (dev / test) |
Swiftmailerbundle | support library for sending letters |
Monolog bundle | Monolog library support for logging |
Scan Difficulties Encountered
Not detected.
Symfony cmf
Description
The purpose of the assembly is to make it easier for the developer to add CMS functionality to the application. Key principles for existing bundles: scalability, usability, good documentation, and good test coverage. The idea of a loosely coupled CMS (decoupling CMS decoupledcms.org ) is being implemented .
A detailed discussion can be found at the link “Symfony CMF. Part 2 and the last " by waitekk .
Installation
Composer | $ composer create-project symfony-cmf / standard-edition $ composer install |
---|---|
Git | $ git clone git: //github.com/symfony-cmf/standard-edition.git $ cd $ composer install |
Basic bundles
Table with names and a brief description
Blockbundle | integrates PHPCR with SonataBlockBundle |
---|---|
Core bundle | provides common helpers methods for displaying content |
Contentbundle | provides basic classes for defining content, for example, the basis of each document is the StaticContent class , which contains the name, body, publication information and a link to the parent document to maintain a hierarchical structure like PHPCR |
Createbundle | integration of create.js , a functional web interface for editing pages using RDFa annotations. In short, it allows you to edit certain elements of the page directly on the published page, without going to the administrative part of the site. |
Mediabundle | Allows you to organize the management of media files from pictures and binary documents (like pdf) to video and mp3. But this requires some additional effort, as the bundle provides control only for pictures and files. |
MenuBundle | integrates PHPCR with KnpMenuBundle |
Routing bundle | expands the capabilities of the router, allows you to create controllers for redirects and create routes depending on the location of the document in PHPCR |
SearchBundle | Site search |
Seobundle | implemented as an add-on for SonataSeoBundle |
SimpleCmsBundle | Allows you to display content, routes, menu items that make up a tree in PHPCR |
SonataDoctrinePhpcrAdminBundle | SonataAdminBundle integration with PHPCR |
Scan Difficulties Encountered
Not detected.
REST API
Description
Step-by-step construction is presented in the tutorial .
Building a REST API is not easy. This paragraph provides an example application with a built REST API.
A blog api example has been implemented. The query processor and its interface are placed in separate classes, the model is presented as an interface of getters and setters implemented by the Page entity. Separating class responsibilities allows you to write better code.
To configure security, an additional layer is required, for example, a bundle that allows you to use Oauth2 ( HWIOAuthBundle ).
The LINK / UNLINK implementation is difficult to remember.
The PATCH method can be varied ( some recommendations ).
Installation
Composer | $ curl -s getcomposer.org/installer | php $ php composer.phar create-project liuggio / symfony2-rest-api-the-best-2013-way -sdev $ cd blog-rest-symfony2 |
---|---|
Git | Git clone github.com/liuggio/symfony2-rest-api-the-best-2013-way.git |
Basic bundles
In addition to the base in the form of Symfony Standard Edition
Table with names and a brief description
FOSRestBundle | creates all necessary configuration routes (YAML or XML) and maps to the appropriate methods |
---|---|
JMSSerializerBundle | needed to serialize responses in json, xml |
NelmioApiDocBundle | generation of documentation for all API methods, recorded in the form of annotations. |
Scan Difficulties Encountered
Not detected.
Evercodelab skeleton
Description
Application framework prepared and used by Evercode.
One of the features is the configured deployment configuration file (capifony) and there are HipChat connection settings for notifying the deployment status and sending critical error logs.
[ Source ]
Installation
Composer | composer.phar create-project evercode / symfony-skeleton path / dev-master |
---|---|
Git | git clone git@github.com: EvercodeLab / symfony-skeleton.git path / |
Basic bundles
Table with names and a brief description
GedmoDoctrineExtensions | expanding the capabilities of Doctrine. Adds such necessary things as Timestampable to automatically set dates when adding and updating records in the database, as well as Tree for the ability to work with trees. |
---|---|
DoctrineFixturesBundle | work with fixtures for the database. It greatly simplifies life at the development stage, when it is necessary to constantly generate some kind of test information. |
DoctrineMigrationsBudnle | generates migrations based on differences between the database and entity mapping. Perhaps the most necessary and important bundle without which development would be much more complicated. |
Fosuserbundle | gives a complete set of functionality for working with users: registration, authorization, etc., in the same vein. |
Sonataadminbundle | gives functionality for creating the administrative part of the site: creating Basic bundles, editing, deleting data, as well as various additional features, for example, exporting data to various formats. This bundle itself has quite flexible options for customizing and customizing to your needs. |
KnpMenuBundle | bundle and library for dynamically generating menus. It uses routes as paths. |
KnpPaginatorBundle | creates dynamic page navigation for the site. |
FOSRestBundle | This bundle provides a set of tools for the rapid development of RESTful APIs and applications. |
Vichuploader bundle | greatly facilitates the download and subsequent use of downloaded files |
caching, resizing and other necessary operations on images. Most often used to create photo previews. | |
EvercodePageBundle | small bundle for working with content pages. Works in conjunction with SonataAdminBundle |
Scan Difficulties Encountered
When using capifony, you may need to tweak it:
- rights to / web, ./app/cache, ./app/logs
- If you use the use: acl parameter in deploy.rb, then you need to run sudo apt-get install acl on the machine for deployment and add the acl flag for the current partition in \ etc \ fstab
- Track the contents of app / config / parameters.yml, because by default the values are taken from app / config / parameters.yml.dist
Sonata sandbox
Description
To demonstrate the work of the sonata project bundles , such a web application was created - a store with rich functionality.
It can greatly simplify the solution of many typical tasks (page layout, creating the admin panel and other CMS functionality, managing media files, etc.), but it requires significant time for familiarization, because the documentation could be better.
Installation
Composer | $ curl -s getcomposer.org/installer | php $ php composer.phar create-project sonata-project / sandbox: 2.3.x-dev or $ DATABASE_NAME = sonata DATABASE_USER = root DATABASE_PASSWORD = "" php composer.phar create-project sonata-project / sandbox: dev-2.4-develop |
---|---|
Archive | $ curl -L github.com/sonata-project/sandbox-build/archive/2.3.tar.gz | tar xzv $ cp app / config / parameters.yml.dist app / config / parameters.yml DB configuration $ vim app / config / parameters.yml data loading $ php bin / load_data.php |
Basic bundles
A large number of bundles, and many of them are auxiliary (dependencies), so I give only the most interesting in terms of creating the ultimate functionality.
Таблица с названиями и кратким описанием
KnpGaufretteBundle | бандл, предоставляет уровень абстракции над файловой системой, позволяет обращаться к файлам одинаково вне зависимости от хранилища (AWS, CloudStorage, … ). Если нижележащая файловая система медленная может еще кэшировать доступ к файлам. |
---|---|
DoctrineFixturesBundle | работа с фикстурами для базы данных. Очень сильно упрощает жизнь на этапе разработки, когда необходимо постоянно генерировать какую-то тестовую информацию. |
DoctrineMigrationsBudnle | генерирует миграции на основе отличий базы данных от мапинга сущностей. Пожалуй самый нужный и важный бандл, без которого разработка была бы намного сложнее. |
FosUserBundle | дает полный набор функционала для работы с пользователями: регистрация, авторизация и прочее в том же духе. |
SonataUserBundle | интегрирует FOSUserBundle в SonataAdminProject |
SonataAdminBundle | дает функционал для создания административной части сайта: созданиеОсновные бандлы, редактирование, удаление данных, а так же различные дополнительные возможности, например, экспортирование данных в различные форматы. Сам по себе данный бандл имеет довольно гибкие возможности по настройке и кастомизации под свои нужды. |
KnpMenuBundle | бандл и библиотека для динамической генерации меню. В качестве путей использует роуты. |
KnpPaginatorBundle | создает динамическую постраничную навигацию для сайта. |
FOSRestBundle | данный бандл предоставляет набор инструментов для быстрой разработки RESTful API и приложений. |
SonataPageBundle | предоставляет управление к сущностям Site (набор Page), Page (бандл предоставляет несколько типов страниц и легче получать функциональность CMS для этих страниц), Block ( контентом управляют сервисы, а Block содержит id сервиса, положение на странице и некоторые найстройки сервиса), Cache ( к каждому блоку в зависимости от контента можно привязать кэширующий сервис) |
SonataNewsBundle | блог платформа на базе Doctrine2 и Symfony2, позволяет управлять видом маршрутов, форматированием текстов, комментариями |
ecommerce | включает различные бандлы необходмые для торговли; Product, Price, Customer, Basket, Delivery, Order, Payment, Invoice |
SonataCacheBundle | unlike other caching solutions, an array with some data is used as the name of the entity, instead of the string or the object itself. And already behind the backend is the task of calculating the identifier for this array. An interesting solution, but I like github.com/FriendsOfSymfony/FOSHttpCacheBundle > FOSHttpCacheBundle more |
Scan Difficulties Encountered
There are no particular difficulties, the application is maintained in a healthy state.
Knp rad project
Description
The bundle significantly reduces the amount of code required to perform standard tasks (sending mail, flash messages, auto-registration of services, creating forms). There is also an assistant for creating missing view templates, if the template was not found, then it can be created right away in the browser directly on the form on the error page.
Among the shortcomings is a small community and the need for additional study.
In addition, SensioGeneratorBundle copes well with the generation of Bundle, Controller, CRUD, Entity, FormType. And its use is more understandable than hiding this code with KnpRadBundle.
[ Wiki project ]
Installation
Composer | $ composer create-project -s dev --prefer-dist --dev knplabs / rad-edition knprad_project $ cd knprad_project |
---|
Basic bundles
Table with names and a brief description
KnpRadBundle | the bundle itself, which allows you to reduce a lot of code (judging by the examples ) |
---|---|
DoctrineFixturesBundle | work with fixtures for the database. It greatly simplifies life at the development stage, when it is necessary to constantly generate some kind of test information. |
MopaBootstrapBundle | twig templates and extensions for more convenient use of twitter bootstrap |
Behat + Mink | Bundles for testing, implement the BDD (behavior-driven development) approach. Instead of a BehatBundle it is better to use: Symfony2Extension |
Scan Difficulties Encountered
No problem.
Symfony2 blog
Description
Based on Symfony SE , a simple blog is created. Following the link to the source there is a step-by-step description of the creation process, but it is better to focus on the Sonata sandbox , in which a small blog is also implemented. Better in the sense that the Sonata project is constantly updating the demo.
[ Source ]
Installation
Git | $ git clone github.com/dsyph3r/symblog.git $ cd symblog |
---|
Basic bundles
Only used by Symfony SE .
Scan Difficulties Encountered
This lesson has been using the old version of Symfony2 (2.0.3) for several years. Not even used composer.