### Display Symfony Project Information Source: https://symfony.com/doc/4.x/setup This command displays general information about the current Symfony project. It's a useful tool for quickly understanding the project's setup and environment when starting work on an existing application. ```bash $ php bin/console about ``` -------------------------------- ### HTTP GET Request Example Source: https://symfony.com/doc/4.x/introduction/http_fundamentals Demonstrates a basic HTTP GET request from a browser to a web server, including the request line and headers like Host, Accept, and User-Agent. ```http GET / HTTP/1.1 Host: xkcd.com Accept: text/html User-Agent: Mozilla/5.0 (Macintosh) ``` -------------------------------- ### Start Docker Containers with Custom Compose File and Project Name Source: https://symfony.com/doc/4.x/setup/symfony_server Demonstrates how to launch Docker containers using a specific Compose file path and project name, overriding default locations. This is useful for complex Docker setups. ```bash # start your containers: COMPOSE_FILE=docker/docker-compose.yaml COMPOSE_PROJECT_NAME=project_name docker-compose up -d ``` -------------------------------- ### Markdown Installation Instructions (Markdown) Source: https://symfony.com/doc/4.x/bundles/best_practices Standardized installation instructions for a Symfony bundle in Markdown format. This section details how to install the bundle using Composer, with separate instructions for applications using Symfony Flex and those that do not. ```markdown Installation ============ Make sure Composer is installed globally, as explained in the [installation chapter](https://getcomposer.org/doc/00-intro.md) of the Composer documentation. Applications that use Symfony Flex ---------------------------------- Open a command console, enter your project directory and execute: ```console $ composer require ``` Applications that don't use Symfony Flex ---------------------------------------- ### Step 1: Download the Bundle Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle: ```console $ composer require ``` ``` -------------------------------- ### Install Symfony Serializer Component Source: https://symfony.com/doc/4.x/components/serializer This command installs the Symfony Serializer component using Composer. Ensure you have Composer installed and a `composer.json` file in your project. ```bash composer require symfony/serializer ``` -------------------------------- ### RST Installation Instructions (RST) Source: https://symfony.com/doc/4.x/bundles/best_practices Standardized installation instructions for a Symfony bundle in reStructuredText (rST) format. This section details how to install the bundle using Composer, with separate instructions for applications using Symfony Flex and those that do not. ```rst Installation ============ Make sure Composer is installed globally, as explained in the [installation chapter](https://getcomposer.org/doc/00-intro.md) of the Composer documentation. Applications that use Symfony Flex ---------------------------------- Open a command console, enter your project directory and execute: .. code-block:: console $ composer require Applications that don't use Symfony Flex ---------------------------------------- ### Step 1: Download the Bundle Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle: .. code-block:: console $ composer require ``` -------------------------------- ### Install Symfony Finder Component Source: https://symfony.com/doc/4.x/components/finder This command installs the Symfony Finder component using Composer. Ensure you have Composer installed and configured for your project. ```bash composer require symfony/finder ``` -------------------------------- ### Install Twig Templating Engine via Composer Source: https://symfony.com/doc/4.x/page_creation This command installs the Twig templating engine for a Symfony project using Composer. Twig is a popular templating language that allows for dynamic HTML generation. Ensure you have Composer installed and accessible in your project's root directory. ```bash composer require twig ``` -------------------------------- ### Install Symfony Messenger Component Source: https://symfony.com/doc/4.x/components/messenger This command installs the Symfony Messenger component using Composer. Ensure you have Composer installed and a `vendor/autoload.php` file if using it outside a Symfony application. ```bash composer require symfony/messenger ``` -------------------------------- ### Install HttpKernel Component Source: https://symfony.com/doc/4.x/components/http_kernel This command installs the HttpKernel component using Composer. Ensure you have Composer installed and configured for your project. This is the standard method for adding Symfony components to a PHP project. ```bash $ composer require symfony/http-kernel ``` -------------------------------- ### Install Symfony Profiler Source: https://symfony.com/doc/4.x/quick_tour/flex_recipes This command installs the Symfony Profiler using Composer. The Profiler provides extensive debugging and performance data through a web debug toolbar and detailed profiler interface. It requires Composer to be installed and configured. ```bash $ composer require profiler ``` -------------------------------- ### Set Up Existing Symfony Project Source: https://symfony.com/doc/4.x/setup Commands to set up an existing Symfony project, typically by cloning the repository and then using Composer to install all project dependencies. This process is essential when collaborating on a project or continuing development on a previously created application. ```bash # clone the project to download its contents $ cd projects/ $ git clone ... # make Composer install the project's dependencies into vendor/ $ cd my-project/ $ composer install ``` -------------------------------- ### Page-Specific JavaScript Entry File Example (Account) Source: https://symfony.com/doc/4.x/frontend/encore/simple-example Example of creating a dedicated JavaScript file for the account page, 'account.js'. Similar to other page-specific entries, this allows for modular code management and optimized asset loading. ```javascript // assets/account.js // custom code for your account page ``` -------------------------------- ### Implement a Symfony Messenger Database Transport Source: https://symfony.com/doc/4.x/messenger/custom-transport This example demonstrates a simplified implementation of the TransportInterface for a database-backed transport. It includes methods for getting messages (`get`), acknowledging them (`ack`), rejecting them (`reject`), and sending new messages (`send`), utilizing a serializer and a fake database connection. ```php use Ramsey\Uuid\Uuid; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp; use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer; use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface; use Symfony\Component\Messenger\Transport\TransportInterface; class YourTransport implements TransportInterface { private $db; private $serializer; /** * @param FakeDatabase $db is used for demo purposes. It is not a real class. */ public function __construct(FakeDatabase $db, SerializerInterface $serializer = null) { $this->db = $db; $this->serializer = $serializer ?? new PhpSerializer(); } public function get(): iterable { // Get a message from "my_queue" $row = $this->db->createQuery( 'SELECT * FROM my_queue WHERE (delivered_at IS NULL OR delivered_at < :redeliver_timeout) AND handled = FALSE' ) ->setParameter('redeliver_timeout', new DateTimeImmutable('-5 minutes')) ->getOneOrNullResult(); if (null === $row) { return []; } $envelope = $this->serializer->decode([ 'body' => $row['envelope'], ]); return [$envelope->with(new TransportMessageIdStamp($row['id']))]; } public function ack(Envelope $envelope): void { $stamp = $envelope->last(TransportMessageIdStamp::class); if (!$stamp instanceof TransportMessageIdStamp) { throw new \LogicException('No TransportMessageIdStamp found on the Envelope.'); } // Mark the message as "handled" $this->db->createQuery('UPDATE my_queue SET handled = TRUE WHERE id = :id') ->setParameter('id', $stamp->getId()) ->execute(); } public function reject(Envelope $envelope): void { $stamp = $envelope->last(TransportMessageIdStamp::class); if (!$stamp instanceof TransportMessageIdStamp) { throw new \LogicException('No TransportMessageIdStamp found on the Envelope.'); } // Delete the message from the "my_queue" table $this->db->createQuery('DELETE FROM my_queue WHERE id = :id') ->setParameter('id', $stamp->getId()) ->execute(); } public function send(Envelope $envelope): Envelope { $encodedMessage = $this->serializer->encode($envelope); $uuid = Uuid::uuid4()->toString(); // Add a message to the "my_queue" table $this->db->createQuery( 'INSERT INTO my_queue (id, envelope, delivered_at, handled) VALUES (:id, :envelope, NULL, FALSE)' ) ->setParameters([ 'id' => $uuid, 'envelope' => $encodedMessage['body'], ]) ->execute(); return $envelope->with(new TransportMessageIdStamp($uuid)); } } ``` -------------------------------- ### Get Cache Item Key and Value Source: https://symfony.com/doc/4.x/components/cache/cache_items Provides an example of retrieving the key and value from a cache item object. This is useful for inspecting the contents of a cache item after it has been retrieved from the pool. ```php $cacheItem = $cache->getItem('exchange_rate'); // ... $key = $cacheItem->getKey(); $value = $cacheItem->get(); ``` -------------------------------- ### Building Assets with Yarn/NPM - Shell Commands Source: https://symfony.com/doc/4.x/frontend/encore/simple-example This section provides shell commands for building project assets using either Yarn or NPM. It includes commands for watching files for changes, running a development server, and creating production builds. ```shell # compile assets and automatically re-compile when files change $ yarn watch # or $ npm run watch # or, run a dev-server that can sometimes update your code without refreshing the page $ yarn dev-server # or $ npm run dev-server # compile assets once $ yarn dev # or $ npm run dev # on deploy, create a production build $ yarn build ``` -------------------------------- ### Configure PostCSS Plugins Source: https://symfony.com/doc/4.x/frontend/encore/postcss Sets up the postcss.config.js file to define which PostCSS plugins to use. This example configures the autoprefixer plugin. Ensure all listed plugins are installed via npm or yarn. ```javascript module.exports = { plugins: { // include whatever plugins you want // but make sure you install these via yarn or npm! // add browserslist config to package.json (see below) autoprefixer: {} } } ``` -------------------------------- ### Basic Encore Configuration - webpack.config.js - JavaScript Source: https://symfony.com/doc/4.x/frontend/encore/simple-example This JavaScript code demonstrates the basic configuration for Encore in a `webpack.config.js` file. It sets the output directory, public path, and defines an entry point for the application assets. ```javascript const Encore = require('@symfony/webpack-encore'); Encore // directory where compiled assets will be stored .setOutputPath('public/build/') // public path used by the web server to access the output path .setPublicPath('/build') .addEntry('app', './assets/app.js') // uncomment this if you want use jQuery in the following example .autoProvidejQuery() ; // ... ``` -------------------------------- ### Running Encore Build Commands (npm/yarn) Source: https://symfony.com/doc/4.x/frontend/encore/simple-example These commands are shortcuts defined in your package.json file for building frontend assets. Common commands include 'dev' and 'watch'. ```bash $ npm run build ``` ```bash $ npm run dev ``` ```bash $ npm run watch ``` ```bash $ yarn add jquery --dev ``` ```bash $ npm install jquery --save-dev ``` -------------------------------- ### Create New Symfony Application with Symfony CLI Source: https://symfony.com/doc/4.x/setup Commands to create a new Symfony application using the Symfony CLI. The `--webapp` flag installs packages for traditional web applications, while omitting it is suitable for microservices, console applications, or APIs. ```bash # run this if you are building a traditional web application $ symfony new my_project_directory --version=4.4 --webapp # run this if you are building a microservice, console application or API $ symfony new my_project_directory --version=4.4 ``` -------------------------------- ### Configure Cache Chain - XML Source: https://symfony.com/doc/4.x/cache Configures a cache chain using XML, starting from Symfony 4.4. This setup defines multiple cache pools and then combines them into a single chain pool for efficient data access. ```xml ``` -------------------------------- ### Create New Symfony Application with Composer Source: https://symfony.com/doc/4.x/setup Alternative commands to create a new Symfony application using Composer. Similar to the Symfony CLI method, `--webapp` installs packages for web applications, while the standard command is for microservices, console applications, or APIs. ```bash # run this if you are building a traditional web application $ composer create-project symfony/website-skeleton:"^4.4" my_project_directory # run this if you are building a microservice, console application or API $ composer create-project symfony/skeleton:"^4.4" my_project_directory ``` -------------------------------- ### Configure Prioritized Transports (XML) Source: https://symfony.com/doc/4.x/messenger This XML configuration illustrates the setup of multiple transports for prioritized message handling, mirroring the functionality of the YAML example. It provides an alternative method for defining Symfony Messenger configurations. ```xml null:// ``` -------------------------------- ### Page-Specific JavaScript Entry File Example Source: https://symfony.com/doc/4.x/frontend/encore/simple-example Example of creating a dedicated JavaScript file for a specific page, such as 'checkout.js'. This file contains custom code relevant only to the checkout process and can be managed as a separate entry point by Webpack. ```javascript // assets/checkout.js // custom code for your checkout page ``` -------------------------------- ### Using ReflectionExtractor for Property Information Source: https://symfony.com/doc/4.x/components/property_info Provides an example of using `ReflectionExtractor` to get property information like list of properties, types, and read/write access from classes using PHP reflection. It supports scalar types and return types from PHP 7. ```php getProperties($class); // Get types for a specific property. $types = $reflectionExtractor->getTypes($class, $property); // Check if a property is readable or writable. $isReadable = $reflectionExtractor->isReadable($class, $property); $isWritable = $reflectionExtractor->isWritable($class, $property); // Check if a property can be initialized via constructor. $isInitializable = $reflectionExtractor->isInitializable($class, $property); ``` -------------------------------- ### Read Object Value Using Getter Source: https://symfony.com/doc/4.x/components/property_access This example shows how PropertyAccessor can read an object's private property by calling its corresponding getter method. It automatically converts snake_case property names (e.g., `first_name`) to camelCase and prefixes with 'get' (e.g., `getFirstName()`). ```php // ... class Person { private $firstName = 'Wouter'; public function getFirstName() { return $this->firstName; } } $person = new Person(); var_dump($propertyAccessor->getValue($person, 'first_name')); // 'Wouter' ``` -------------------------------- ### Install Sass Dependencies for Encore Source: https://symfony.com/doc/4.x/frontend/encore/simple-example Provides commands to install the necessary dependencies (`sass-loader` and `sass`) for enabling Sass support in Symfony Encore. It includes instructions for both Yarn and npm package managers. ```bash # if you use the Yarn package manager $ yarn add sass-loader@^12.0.0 sass --dev $ yarn encore dev --watch # if you use the npm package manager $ npm install sass-loader@^12.0.0 sass --save-dev $ npm run watch ``` -------------------------------- ### Enable Vue.js with JSX Support in webpack.config.js Source: https://symfony.com/doc/4.x/frontend/encore/vuejs This configuration enables Vue.js with JSX support in your webpack.config.js. By passing an options object with `useJsx: true` to `enableVueLoader()`, you can start using JSX syntax in your Vue components. Remember to restart Encore to install required dependencies. ```javascript // webpack.config.js // ... Encore // ... .addEntry('main', './assets/main.js') - .enableVueLoader() + .enableVueLoader(() => {}, { + useJsx: true + }) ; ``` -------------------------------- ### Initialize and Use Filesystem Component Source: https://symfony.com/doc/4.x/components/filesystem Demonstrates the basic usage of the Symfony Filesystem component. It initializes the Filesystem class and shows an example of creating a temporary directory, including error handling for potential IO exceptions. ```php use Symfony\Component\Filesystem\Exception\IOExceptionInterface; use Symfony\Component\Filesystem\Filesystem; $filesystem = new Filesystem(); try { $filesystem->mkdir(sys_get_temp_dir().'/'.random_int(0, 1000)); } catch (IOExceptionInterface $exception) { echo "An error occurred while creating your directory at ".$exception->getPath(); } ``` -------------------------------- ### Symfony Session Management Quick Example (PHP) Source: https://symfony.com/doc/4.x/components/http_foundation/sessions Demonstrates the basic usage of the Symfony Session class for starting a session, setting and retrieving attributes, and adding/retrieving flash messages. It replaces native PHP session functions with Symfony's object-oriented interface. ```php use Symfony\Component\HttpFoundation\Session\Session; $session = new Session(); $session->start(); // set and get session attributes $session->set('name', 'Drak'); $session->get('name'); // set flash messages $session->getFlashBag()->add('notice', 'Profile updated'); // retrieve messages foreach ($session->getFlashBag()->get('notice', []) as $message) { echo '
'.$message.'
'; } ``` -------------------------------- ### Importing JavaScript Modules and Using jQuery (app.js) Source: https://symfony.com/doc/4.x/frontend/encore/simple-example Import external libraries like jQuery and local modules like greet.js into your main application file. This example demonstrates using jQuery to prepend a greeting message to the page body upon document ready. ```javascript // assets/app.js // ... + // loads the jquery package from node_modules + import $ from 'jquery'; + // import the function from greet.js (the .js extension is optional) + // ./ (or ../) means to look for a local file + import greet from './greet'; + $(document).ready(function() { + $('body').prepend('

'+greet('jill')+'

'); + }); ``` -------------------------------- ### Get Clicked Submit Button Name in Symfony Source: https://symfony.com/doc/4.x/form/multiple_buttons This PHP example illustrates an alternative method in Symfony to identify the clicked submit button by retrieving its name using `getClickedButton()->getName()`. It also provides a way to compare button objects for nested forms. ```php if ($form->getClickedButton() && 'saveAndAdd' === $form->getClickedButton()->getName()) { // ... } // when using nested forms, two or more buttons can have the same name; // in those cases, compare the button objects instead of the button names if ($form->getClickedButton() === $form->get('saveAndAdd')){ // ... } ``` -------------------------------- ### Triggering Deprecation Errors with @trigger_error (PHP) Source: https://symfony.com/doc/4.x/contributing/code/conventions This example demonstrates how to trigger a user-level deprecation error in PHP using `@trigger_error`. This is crucial for informing users about deprecated code usage at runtime and guiding them towards replacements. The error message includes the deprecated class/method and its suggested replacement. ```php @trigger_error(sprintf('The "%s" class is deprecated since Symfony 2.8, use "%s" instead.', Deprecated::class, Replacement::class), E_USER_DEPRECATED); ``` -------------------------------- ### Symfony HttpKernel Full Working Example (PHP) Source: https://symfony.com/doc/4.x/components/http_kernel This example demonstrates how to set up a complete, working HttpKernel instance. It includes configuring routes, creating a request, and handling the request-response cycle. Dependencies include Symfony's HttpKernel, Routing, EventDispatcher, and HttpFoundation components. ```php use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Controller\ArgumentResolver; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpKernel\EventListener\RouterListener; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; $routes = new RouteCollection(); $routes->add('hello', new Route('/hello/{name}', [ '_controller' => function (Request $request) { return new Response( sprintf("Hello %s", $request->get('name')) ); } ])); $request = Request::createFromGlobals(); $matcher = new UrlMatcher($routes, new RequestContext()); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new RouterListener($matcher, new RequestStack())); $controllerResolver = new ControllerResolver(); $argumentResolver = new ArgumentResolver(); $kernel = new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); ``` -------------------------------- ### Check Symfony Requirements with CLI Source: https://symfony.com/doc/4.x/setup This command checks if your computer meets all the technical requirements for developing and running a Symfony application. It is executed via the Symfony CLI tool. ```bash $ symfony check:requirements ``` -------------------------------- ### Define Validation Metadata via Annotations in a Class Source: https://symfony.com/doc/4.x/components/validator/resources This example shows how to define validation metadata using annotations directly within a class's doc blocks. Constraints like `AssertNotBlank` are applied to properties using the `@` syntax. This requires `doctrine/annotations` and `doctrine/cache` to be installed and configured. ```php use SymfonyComponentValidatorConstraints as Assert; // ... class User { /** * @AssertNotBlank */ protected $name; } ``` -------------------------------- ### PHP: Blog Post Show Controller (show.php) Source: https://symfony.com/doc/4.x/introduction/from_flat_php_to_symfony This controller file fetches a single blog post using its ID from the query parameter and then renders the post using a template. It depends on the `model.php` file for data retrieval and a `templates/show.php` file for presentation. It handles the request to display an individual blog post. ```php // show.php require_once 'model.php'; $post = get_post_by_id($_GET['id']); require 'templates/show.php'; ``` -------------------------------- ### Control Login Redirect with Request Parameters Source: https://symfony.com/doc/4.x/security/form_login Allows specifying the redirect URL via GET or POST request parameters, like `_target_path`. This provides dynamic control over post-login redirection. A Twig template example shows how to implement this with a hidden form field. ```http http://example.com/some/path?_target_path=/dashboard ``` ```twig {# templates/security/login.html.twig #}
{# ... #}
``` -------------------------------- ### Get Public Asset Path with `asset` Twig Function Source: https://symfony.com/doc/4.x/reference/twig_reference The `asset` Twig function returns the public path for a given asset (CSS, JS, image, etc.). It accounts for application installation location and optional asset package base paths, supporting cache busting implementations. ```twig {{ asset(path, packageName = null) }} ``` -------------------------------- ### Setting Time Label in Symfony DateTimeType Source: https://symfony.com/doc/4.x/reference/forms/types/datetime This snippet demonstrates how to set a custom label for the time part of a DateTimeType field in a Symfony form. It uses the 'time_label' option to provide a user-friendly label. The default behavior is to 'guess' the label from the field name, but this example explicitly sets it to 'Starts On'. ```php use Symfony\Component\Form\Extension\Core\Type\DateTimeType; $builder->add('startDateTime', DateTimeType::class, [ 'time_label' => 'Starts On', ]); ``` -------------------------------- ### Setting up Symfony Console Application (PHP) Source: https://symfony.com/doc/4.x/components/console/usage This snippet demonstrates how to initialize a Symfony Console application by including the autoloader and creating an Application instance. It assumes a basic setup for running commands via the CLI. ```php #!/usr/bin/env php run(); ``` -------------------------------- ### Symfony Front Controller (PHP) Source: https://symfony.com/doc/4.x/introduction/from_flat_php_to_symfony The entry point of the Symfony application, responsible for bootstrapping the framework and handling incoming requests. It initializes the Symfony Kernel and uses it to process the request, returning the HTTP response. This file is typically not modified after initial setup. ```php // public/index.php require_once __DIR__.'/../app/bootstrap.php'; require_once __DIR__.'/../src/Kernel.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new Kernel('prod', false); $kernel->handle(Request::createFromGlobals())->send(); ``` -------------------------------- ### Configure Route Annotations with XML in Symfony Source: https://symfony.com/doc/4.x/routing This XML configuration achieves the same route loading setup as the YAML example. It uses the tag to specify the controller resource, type, prefix, name prefix, and locale requirements. The 'exclude' attribute is used to prevent specific controller files from being processed. ```xml en|es|fr ``` -------------------------------- ### Install Symfony Filesystem Component Source: https://symfony.com/doc/4.x/components/filesystem Installs the Symfony Filesystem component using Composer. This command downloads and integrates the necessary files into your project's vendor directory. ```bash composer require symfony/filesystem ``` -------------------------------- ### Test New Symfony Version with Git Branching (Bash) Source: https://symfony.com/doc/4.x/setup/unstable_versions This example demonstrates a Git workflow for safely testing a new Symfony version. It involves creating a new branch, updating composer.json, running composer update, and then reverting the changes by checking out the master branch and deleting the test branch. ```bash $ cd projects/my_project/ $ git checkout -b testing_new_symfony # ... update composer.json configuration $ composer update "symfony/*" # ... after testing the new Symfony version $ git checkout master $ git branch -D testing_new_symfony ``` -------------------------------- ### Full Symfony Front Controller Setup in PHP Source: https://symfony.com/doc/4.x/create_framework/templating This comprehensive PHP script sets up the front controller for a Symfony application. It includes autoloading, request handling, route definition, context setup, URL matching, and controller invocation with error handling. It also defines a `render_template` helper function. ```php // example.com/web/front.php require_once __DIR__.'/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing; function render_template($request) { extract($request->attributes->all(), EXTR_SKIP); ob_start(); include sprintf(__DIR__.'/../src/pages/%s.php', $_route); return new Response(ob_get_clean()); } $request = Request::createFromGlobals(); $routes = include __DIR__.'/../src/app.php'; $context = new Routing\RequestContext(); $context->fromRequest($request); $matcher = new Routing\Matcher\UrlMatcher($routes, $context); try { $request->attributes->add($matcher->match($request->getPathInfo())); $response = call_user_func($request->attributes->get('_controller'), $request); ``` -------------------------------- ### Configuring TagAwareAdapter with Separate Adapters Source: https://symfony.com/doc/4.x/components/cache/cache_invalidation This example illustrates how to configure the `TagAwareAdapter` using two distinct cache adapters: one for storing cached items (e.g., `FilesystemAdapter`) and another for storing tags (e.g., `RedisAdapter`). This setup allows for efficient tag invalidation, especially when dealing with large cached items. ```php use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter; use Symfony\Component\Cache\Adapter\TagAwareAdapter; $cache = new TagAwareAdapter( // Adapter for cached items new FilesystemAdapter(), // Adapter for tags new RedisAdapter('redis://localhost') ); ``` -------------------------------- ### Front Controller Routing and Request Handling (PHP) Source: https://symfony.com/doc/4.x/introduction/from_flat_php_to_symfony This PHP code snippet demonstrates a basic front controller implementation in `index.php`. It handles routing for different URIs (`/index.php` for list, `/index.php/show` for show), loads global libraries, and renders appropriate pages or a 404 error. It expects `model.php` and `controllers.php` to be included. ```php // index.php // load and initialize any global libraries require_once 'model.php'; require_once 'controllers.php'; // route the request internally $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); if ('/index.php' === $uri) { list_action(); } elseif ('/index.php/show' === $uri && isset($_GET['id'])) { show_action($_GET['id']); } else { header('HTTP/1.1 404 Not Found'); echo '

Page Not Found

'; } ``` -------------------------------- ### Install Symfony Recipes using Composer Source: https://symfony.com/doc/4.x/setup/flex_private_recipes Commands to install or update Symfony recipes in your project. Use 'composer update' if your private bundles/packages are not yet installed, or 'composer recipes' if they are already installed and you only need to add new private recipes. ```bash $ composer update ``` ```bash $ composer recipes ``` -------------------------------- ### Set Session Cache Limiter in Symfony Source: https://symfony.com/doc/4.x/components/http_foundation/session_configuration This example shows how to configure the session cache limiter using NativeSessionStorage. The cache_limiter option controls which HTTP caching headers are sent with the response when a session is started. Setting it to an empty string ('') means no headers are sent, allowing manual control via Response objects. ```php use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; // Get the current PHP session cache limiter setting $options['cache_limiter'] = session_cache_limiter(); // Initialize NativeSessionStorage with the cache limiter option $sessionStorage = new NativeSessionStorage($options); ``` -------------------------------- ### PHP: Displaying a list of posts from a database Source: https://symfony.com/doc/4.x/introduction/from_flat_php_to_symfony This PHP script connects to a MySQL database, fetches a list of posts, and stores them in an array. It then includes a separate HTML file to present the data. Dependencies include a PDO-compatible database driver and a 'templates/list.php' file for presentation. ```php // index.php $connection = new PDO("mysql:host=localhost;dbname=blog_db", 'myuser', 'mypassword'); $result = $connection->query('SELECT id, title FROM post'); $posts = []; while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $posts[] = $row; } $connection = null; // include the HTML presentation code require 'templates/list.php'; ``` -------------------------------- ### Configure Symfony to Trust All Proxies (PHP) Source: https://symfony.com/doc/4.x/deployment/proxies This example shows how to configure Symfony to trust all incoming requests when IP addresses are dynamic, such as with AWS Elastic Load Balancing. It requires careful security setup at the web server level to ensure only trusted proxies can forward requests. Support for `REMOTE_ADDR` was added in Symfony 4.4. ```php // public/index.php // ... Request::setTrustedProxies( // trust *all* requests (the 'REMOTE_ADDR' string is replaced at // run time by $_SERVER['REMOTE_ADDR']) ['127.0.0.1', 'REMOTE_ADDR'], // if you're using ELB, otherwise use a constant from above Request::HEADER_X_FORWARDED_AWS_ELB ); ``` -------------------------------- ### Symfony Front Controller Setup Source: https://symfony.com/doc/4.x/configuration/micro_kernel_trait This PHP script serves as the entry point for a Symfony application. It handles autoloading, registers annotation loaders, bootstraps the Symfony kernel, processes incoming requests, and sends back the HTTP response. It's crucial for running the application. ```php // public/index.php use App\Kernel; use Doctrine\Common\Annotations\AnnotationRegistry; use Symfony\Component\HttpFoundation\Request; $loader = require __DIR__.'/../vendor/autoload.php'; // auto-load annotations AnnotationRegistry::registerLoader([$loader, 'loadClass']); $kernel = new Kernel('dev', true); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); ``` -------------------------------- ### Start Symfony Local Web Server Source: https://symfony.com/doc/4.x/configuration/micro_kernel_trait This command initiates the Symfony local web server from the public directory of your project. It's a convenient way to test your Symfony application locally. After starting, you can access your application via a specified URL in your browser. ```bash cd public/ $ symfony server:start ``` -------------------------------- ### Installing Composer Dependencies Source: https://symfony.com/doc/4.x/introduction/from_flat_php_to_symfony This command installs all the dependencies defined in the composer.json file, including the Symfony HttpFoundation component. It also generates an autoloader file (`vendor/autoload.php`) for convenient class loading. ```bash $ composer install ``` -------------------------------- ### Install Symfony Validator Component Source: https://symfony.com/doc/4.x/components/validator This command installs the Symfony Validator component using Composer. Ensure you have Composer installed and configured for your project. ```bash composer require symfony/validator ``` -------------------------------- ### Install Symfony Console Component Source: https://symfony.com/doc/4.x/components/console This command installs the Symfony Console component using Composer. Ensure Composer is installed and accessible in your environment. ```bash $ composer require symfony\/console ``` -------------------------------- ### Stimulus Controller Initialization Example Source: https://symfony.com/doc/4.x/frontend/encore/simple-example Demonstrates how to define a Stimulus controller in JavaScript, specifying targets and actions. This controller is initialized automatically by Stimulus when an element with the corresponding data-controller attribute is present on the page. ```javascript // assets/controllers/say-hello-controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['name', 'output'] greet() { this.outputTarget.textContent = `Hello, ${this.nameTarget.value}!` } } ``` -------------------------------- ### Configure API Token Authentication in security.xml Source: https://symfony.com/doc/4.x/security/guard_authentication This XML configuration achieves the same API token authentication setup as the YAML version. It defines a 'main' firewall with anonymous access, logout, and the App\Security\TokenAuthenticator. Comments indicate how to enable stateless mode by adding 'stateless="true"' to the firewall element. ```xml App\Security\TokenAuthenticator ``` -------------------------------- ### Start Symfony Local Web Server (CLI) Source: https://symfony.com/doc/4.x/create_framework/front_controller Starts the Symfony local web server on a specified port and allows passthrough for a front controller script. Useful for local development and testing routing configurations. ```bash $ symfony server:start --port=4321 --passthru=front.php ``` -------------------------------- ### Install Symfony Lock Component Source: https://symfony.com/doc/4.x/components/lock Installs the Symfony Lock component using Composer. This is the primary method to add the component to your project. Ensure you have Composer installed. ```bash composer require symfony/lock ``` -------------------------------- ### Install Symfony DomCrawler Component Source: https://symfony.com/doc/4.x/components/dom_crawler This command installs the Symfony DomCrawler component using Composer. Ensure you have Composer installed and configured for your PHP project. ```bash $ composer require symfony\/dom-crawler ``` -------------------------------- ### Configure HTTP Method Restrictions for Routes (Annotations, YAML, XML, PHP) Source: https://symfony.com/doc/4.x/routing Specify which HTTP methods (e.g., GET, POST, PUT) a route should respond to. This is crucial for API endpoints or forms that require specific HTTP verbs. The examples demonstrate configuring these restrictions using annotations in a controller, as well as in YAML, XML, and PHP route definitions. ```php // src/Controller/BlogApiController.php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class BlogApiController extends AbstractController { /** * @Route("/api/posts/{id}", methods={"GET","HEAD"}) */ public function show(int $id): Response { // ... return a JSON response with the post } /** * @Route("/api/posts/{id}", methods={"PUT"}) */ public function edit(int $id): Response { // ... edit a post } } ``` ```yaml # config/routes.yaml api_post_show: path: /api/posts/{id} controller: App\Controller\BlogApiController::show methods: GET|HEAD api_post_edit: path: /api/posts/{id} controller: App\Controller\BlogApiController::edit methods: PUT ``` ```xml ``` ```php // config/routes.php use App\Controller\BlogApiController; use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; return function (RoutingConfigurator $routes) { $routes->add('api_post_show', '/api/posts/{id}') ->controller([BlogApiController::class, 'show']) ->methods(['GET', 'HEAD']) ; $routes->add('api_post_edit', '/api/posts/{id}') ->controller([BlogApiController::class, 'edit']) ->methods(['PUT']) ; }; ``` -------------------------------- ### Install Symfony Asset Package Source: https://symfony.com/doc/4.x/templates Command to install the Symfony asset package, which provides Twig functions for managing static asset URLs. ```bash $ composer require symfony/asset ```