Symfony Core Flashcards
Command to get the list of all services that we can access?
project_dir$: ./bin/console debug:autowiring
How to install a bundle?
composer require author/nameofBundle
Configuring Symfony
Symfony applications are configured with the files stored in the config/. The routes.yaml file defines the routing configuration; the services.yaml file configures the services of the service container; the bundles.php file enables/ disables packages in your application.
You’ll be working most in the config/packages/ directory. This directory stores the configuration of every package installed in your application.
parameters (example: env(APP_TIMEZONE): ‘ ‘) inside services.yaml will be called from
docker\app.env example: APP_TIMEZONE=Asia/Singapore
Show the full list of all the services in the container. service id is on the left.
project_dir$: ./bin/console debug:container –show-private
our current configs
./bin/console debug:config framework
src\Kernel.php
configureContainer for loading configs
If want to see all the env variables that are currently set and Symfony version +System info details
./bin/console about
MakerBundle makes our life easier by generating code
composer require maker –dev
Type casting: Advanced environment variables example:
app. connection.port: ‘%env(int:DATABASE_PORT)%’
bool: , int:, float: and string: casting.
app. secrets: ‘%env(json:file:SECRETS_FILE)%’
Symfony debugging tools
install: compose require debug –dev
search debug on https://symfony.sh and view debug-pack which contains only composer.json file.
start Symfony server and install API Platform
symfony serve -d
composer require api
then go to locahost:8000/api to see API platform
create entity: ./bing//console make:entity
migration:
- composer require migrations
- ./bin/console/ make:migration
To list all routers
./bin/console debug:router
Service tags are a way to tell Symfony or other third-party bundles that your service should be registered in some special way.
Example: # config/services.yaml services: App\Twig\AppExtension: tags: ['twig.extension']
service container
Your application is full of useful objects: a “Mailer” object might help you send emails while another object might help you save things to the database. Almost everything that your app “does” is actually done by one of these objects. And each time you install a new bundle, you get access to even more!
In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!
there is another type of parameter related to services. In YAML config, any string which starts with @ is considered as the ID of a service, instead of a regular string.
In YAML config, any string which starts with @ is considered as the ID of a service, instead of a regular string.
built-in tag
kernel.event_listener
Purpose: To listen to different events/hooks in Symfony
During the execution of a Symfony application, different events are triggered and you can also dispatch custom events. This tag allows you to hook your own classes into any of those events.
Symfony Config component
The Config component provides several classes to help you find, load, combine, fill and validate configuration values of any kind, whatever their source may be (YAML, XML, INI files, or for instance a database).
In order to load service configuration, you have to create a Dependency Injection (DI) Extension for your bundle.
By default, the Extension class must follow these conventions
It has to live in the DependencyInjection namespace of the bundle; It has to implement the ExtensionInterface, which is usually achieved by extending the Extension class; The name is equal to the bundle name with the Bundle suffix replaced by Extension (e.g. the Extension class of the AcmeBundle would be called AcmeExtension and the one for AcmeHelloBundle would be called AcmeHelloExtension).
DI - Application-level Configuration?
Application level config is loaded from the config directory. Multiple files are loaded which are then merged when the extensions are processed. This allows for different configuration for different environments e.g. dev, prod.
Working with a Cached Container
Before building it, the kernel checks to see if a cached version of the container exists. The HttpKernel has a debug setting and if this is false, the cached version is used if it exists. If debug is true then the kernel checks to see if configuration is fresh and if it is, the cached version of the container is used. If not then the container is built from the application-level configuration and the bundles’s extension configuration.
Bundle-level Configuration with Extensions
By convention, each bundle contains an Extension class which is in the bundle’s DependencyInjection directory. These are registered with the ContainerBuilder when the kernel is booted. When the ContainerBuilder is compiled, the application-level configuration relevant to the bundle’s extension is passed to the Extension which also usually loads its own config file(s), typically from the bundle’s Resources/config directory. The application-level config is usually processed with a Configuration object also stored in the bundle’s DependencyInjection directory.
Compiler Passes to Allow Interaction between Bundles
Compiler passes are used to allow interaction between different bundles as they cannot affect each other’s configuration in the extension classes. One of the main uses is to process tagged services, allowing bundles to register services to be picked up by other bundles, such as Monolog loggers, Twig extensions and Data Collectors for the Web Profiler. Compiler passes are usually placed in the bundle’s DependencyInjection/Compiler directory.
Compilation and Caching
After the compilation process has loaded the services from the configuration, extensions and the compiler passes, it is dumped so that the cache can be used next time. The dumped version is then used during subsequent requests as it is more efficient.
Service Parameters
In addition to holding service objects, the container also holds configuration, called parameters. However, there is another type of parameter related to services. In YAML config, any string which starts with @ is considered as the ID of a service, instead of a regular string.
Importing Many Services at once with resource
you can import many services at once by using the resource key. The value of the resource and exclude options can be any valid glob pattern. This can be used to quickly make many classes available as services and apply some default configuration. The id of each service is its fully-qualified class name. You can override any service that’s imported by using its id (class name) below. If you override a service, none of the options (e.g. public) are inherited from the import (but the overridden service does still inherit from _defaults).
You can also exclude certain paths. This is optional, but will slightly increase performance in the dev environment: excluded paths are not tracked and so modifying them will not cause the container to be rebuilt.
Routing
// generate a URL with route arguments
$userProfilePage = $this->generateUrl(‘user_profile’, [
‘username’ => $user->getUsername(),
]);
If your controller does not extend from AbstractController, you’ll need to fetch services in your controller (type-hinting constructor:
// generate a URL with route arguments
$userProfilePage = $this->router->generate(‘user_profile’, [
‘username’ => $user->getUsername(),
]);
OptionsResolver setNormalizer
class Mailer { // ... public function configureOptions(OptionsResolver $resolver) { // ... $resolver->setNormalizer('host', function (Options $options, $value) { if ('http://' !== substr($value, 0, 7) && 'https://' !== substr($value, 0, 8)) { if ('ssl' === $options['encryption']) { $value = 'https://'.$value; } else { $value = 'http://'.$value; } }
return $value; });