### Install Symfony Package with Flex Source: https://symfony.com/doc/8.0/setup Installs a package into a Symfony application using Symfony Flex. Flex automates the setup process by using predefined 'recipes'. This command requires Composer and the Symfony Flex plugin to be installed in the project. ```bash cd my-project/ composer require logger ``` -------------------------------- ### Start Symfony Local Web Server Source: https://symfony.com/doc/8.0/setup Starts the local development web server provided by the Symfony CLI. This server supports HTTP/2, concurrent requests, and TLS/SSL. Navigate to http://localhost:8000/ in your browser after starting. Stop the server by pressing Ctrl+C. ```bash cd my-project/ symfony server:start ``` -------------------------------- ### API Platform Package Configuration Example Source: https://symfony.com/doc/8.0/configuration Shows an example of a default configuration file created by the 'API Platform' bundle when installed via Symfony Flex. This file, api_platform.yaml, specifies mapping paths for entity directories. ```yaml # config/packages/api_platform.yaml api_platform: mapping: paths: ['%kernel.project_dir%/src/Entity'] ``` -------------------------------- ### Install Console Completion for Symfony CLI Tools (Bash Example) Source: https://symfony.com/doc/8.0/console Provides instructions for enabling command auto-completion in the terminal for Symfony Console commands and other PHP tools that use the component. This requires a one-time setup and enhances productivity by allowing users to complete command names and options by pressing the Tab key. ```bash $ php vendor/bin/phpstan completion --help $ composer completion --help ``` -------------------------------- ### Check Symfony Project Requirements Source: https://symfony.com/doc/8.0/setup This command checks if your local environment meets all the requirements for developing and running a Symfony application. It's a quick way to ensure your setup is compatible. ```bash $ symfony check:requirements ``` -------------------------------- ### Install Verify Email Bundle and Make Registration Form Source: https://symfony.com/doc/8.0/security Installs the SymfonyCastsVerifyEmailBundle and uses the make:registration-form command to set up a registration controller. This is a common setup for user registration with email verification. ```bash $ composer require symfonycasts/verify-email-bundle $ php bin/console make:registration-form ``` -------------------------------- ### Install Symfony Test Pack Source: https://symfony.com/doc/8.0/testing Installs the necessary packages for testing in a Symfony application, including PHPUnit. This is a foundational step before writing any tests. ```bash $ composer require --dev symfony/test-pack ``` -------------------------------- ### Load Product Entities using DoctrineFixturesBundle Source: https://symfony.com/doc/8.0/testing An example of a `ProductFixture` class that extends `DoctrineBundleFixturesBundleFixture` and uses the `ObjectManager` to persist new `Product` entities into the database. ```php // src/DataFixtures/ProductFixture.php namespace App\DataFixtures; use App\Entity\Product; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; class ProductFixture extends Fixture { public function load(ObjectManager $manager): void { $product = new Product(); $product->setName('Priceless widget'); $product->setPrice(14.50); $product->setDescription('Ok, I guess it *does* have a price'); $manager->persist($product); // add more products $manager->flush(); } } ``` -------------------------------- ### Create Symfony Application with Composer (Microservice/API) Source: https://symfony.com/doc/8.0/setup Use Composer to create a new Symfony project for microservices, console applications, or APIs. This method installs only the essential packages. ```bash $ composer create-project symfony/skeleton:"8.0.*" my_project_directory ``` -------------------------------- ### Notifier Configuration Example Source: https://symfony.com/doc/8.0/notifier Example of how to configure notifier transports using Symfony's secrets and environment variables. ```APIDOC ## Notifier Configuration ### Description This section provides guidance on securely configuring notifier transports using Symfony's secrets and environment variables. ### Secure Storage Use Symfony configuration secrets to securely store your API tokens. ### Webhook Support Some third-party transports support status callbacks via webhooks. Refer to the Webhook documentation for more details. ### Enabling Transports To enable a texter, add the correct DSN in your `.env` file and configure the `texter_transports` in your `config/packages/notifier.yaml`. #### `.env` Example ```dotenv TWILIO_DSN=twilio://SID:TOKEN@default?from=FROM ``` #### `config/packages/notifier.yaml` Example ```yaml framework: notifier: texter_transports: - twilio ``` ``` -------------------------------- ### Basic WebTestCase Structure and Assertions in PHP Source: https://symfony.com/doc/8.0/testing This PHP code demonstrates a basic application test using Symfony's `WebTestCase`. It shows how to create a test client, make a GET request to the root URL, and assert that the response is successful and contains specific text in the `h1` tag. ```php namespace App\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class PostControllerTest extends WebTestCase { public function testSomething(): void { // This calls KernelTestCase::bootKernel(), and creates a // "client" that is acting as the browser $client = static::createClient(); // Request a specific page $crawler = $client->request('GET', '/'); // Validate a successful response and some content $this->assertResponseIsSuccessful(); $this->assertSelectorTextContains('h1', 'Hello World'); } } ``` -------------------------------- ### Install Symfony HttpClient Component Source: https://symfony.com/doc/8.0/http_client Installs the Symfony HttpClient component using Composer. This is the first step to using the client in your PHP project. ```bash $ composer require symfony/http-client ``` -------------------------------- ### Install Symfony String Component Source: https://symfony.com/doc/8.0/components/string This command installs the Symfony String component using Composer. Ensure you have Composer installed and configured for your project. If using outside a Symfony application, remember to include the Composer autoloader. ```bash composer require symfony/string ``` -------------------------------- ### Install Symfony Webhook Component Source: https://symfony.com/doc/8.0/webhook This command installs the Symfony Webhook component using Composer. Ensure you have Composer installed and configured for your project. ```bash composer require symfony/webhook ``` -------------------------------- ### Install HttpFoundation Component for Sessions Source: https://symfony.com/doc/8.0/session This command installs the Symfony HttpFoundation component, which is required for using the session subsystem. ```bash composer require symfony/http-foundation ``` -------------------------------- ### Install Symfony LDAP Component Source: https://symfony.com/doc/8.0/security/ldap This command installs the LDAP component for Symfony applications using Composer. Ensure you have Composer installed and configured for your project. ```bash $ composer require symfony/ldap ``` -------------------------------- ### Install HttpKernel Component with Composer Source: https://symfony.com/doc/8.0/components/http_kernel This command installs the HttpKernel component using Composer, the dependency manager for PHP. Ensure you have Composer installed and configured in your project. ```bash composer require symfony/http-kernel ``` -------------------------------- ### YAML Translation File Example (Simple) Source: https://symfony.com/doc/8.0/translation A basic example of a YAML file for translations in Symfony, demonstrating a simple key-value pair for a single translation. ```yaml Symfony is great: Symfony est génial ``` -------------------------------- ### DynamoDB Lock Storage Installation Source: https://symfony.com/doc/8.0/components/lock Instructions to install the DynamoDB lock store via Composer. ```bash $ composer require symfony/amazon-dynamo-db-lock ``` -------------------------------- ### Install Symfony Debug Pack Source: https://symfony.com/doc/8.0/setup Installs a collection of packages for debugging features in a Symfony application using a Composer 'pack'. This command utilizes Symfony Flex to unpack the meta-package and add individual dependencies to your project. ```bash composer require --dev debug ``` -------------------------------- ### Install Symfony Scheduler Component Source: https://symfony.com/doc/8.0/scheduler This command installs the Symfony Scheduler component using Composer. In Symfony Flex applications, this also sets up an initial schedule configuration. ```bash composer require symfony/scheduler ``` -------------------------------- ### Install Symfony Security Bundle Source: https://symfony.com/doc/8.0/security This command installs the Symfony SecurityBundle, which provides authentication and authorization features for your application. It's a crucial first step in securing your Symfony project. ```bash composer require symfony\/security-bundle ``` -------------------------------- ### Install Symfony Form Component Source: https://symfony.com/doc/8.0/forms Installs the Symfony Form component using Composer. This is a prerequisite for using Symfony's form handling features. ```bash $ composer require symfony/form ``` -------------------------------- ### Initialize and Start Session (Standalone PHP) Source: https://symfony.com/doc/8.0/session Shows how to instantiate and manually start a session object when using the HttpFoundation component outside of the Symfony framework. ```php use Symfony\Component\HttpFoundation\Session\Session; $session = new Session(); $session->start(); ``` -------------------------------- ### Set up Existing Symfony Project with Git and Composer Source: https://symfony.com/doc/8.0/setup These commands outline the process for setting up an existing Symfony project. It involves cloning the repository and then using Composer to install all project dependencies. ```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 ``` -------------------------------- ### Install DAMADoctrineTestBundle for Automated Database Reset Source: https://symfony.com/doc/8.0/testing Installs the DAMADoctrineTestBundle via Composer, which automates database transaction management for tests, ensuring each test starts with an unmodified database. ```bash $ composer require --dev dama/doctrine-test-bundle ``` -------------------------------- ### Create a New Symfony Project with the Demo Application Source: https://symfony.com/doc/8.0/setup Initialize a new Symfony project using the provided Symfony CLI command. This command bootstraps a new project based on the Symfony Demo application, which serves as an excellent learning resource for new Symfony developers. ```bash $ symfony new my_project_directory --demo ``` -------------------------------- ### Display Symfony Project Information Source: https://symfony.com/doc/8.0/setup This command displays general information about the Symfony project, including details about its configuration and installed components. It's useful when working with an existing project for the first time. ```bash $ php bin/console about ``` -------------------------------- ### Create a New Symfony Microservice or API Source: https://symfony.com/doc/8.0/setup This command creates a new Symfony project suitable for microservices, console applications, or APIs. It installs a leaner set of default packages. ```bash $ symfony new my_project_directory --version="8.0.*" ``` -------------------------------- ### Install DoctrineFixturesBundle for Test Data Source: https://symfony.com/doc/8.0/testing Installs the DoctrineFixturesBundle via Composer, which provides tools for creating and loading test data (fixtures) into the database. ```bash $ composer require --dev doctrine/doctrine-fixtures-bundle ``` -------------------------------- ### Create a New Symfony Web Application Source: https://symfony.com/doc/8.0/setup Use this command to create a new Symfony project intended for traditional web applications. It installs additional packages needed for web development. ```bash $ symfony new my_project_directory --version="8.0.*" --webapp ``` -------------------------------- ### Initialize and Use Filesystem Component Source: https://symfony.com/doc/8.0/components/filesystem Demonstrates initializing the Filesystem and Path classes from the Symfony component to create a temporary directory. Includes basic error handling for IO exceptions. ```php use Symfony\Component\Filesystem\Exception\IOExceptionInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Path; $filesystem = new Filesystem(); try { $filesystem->mkdir( Path::normalize(sys_get_temp_dir().'/'." . "random_int(0, 1000)) ); } catch (IOExceptionInterface $exception) { echo "An error occurred while creating your directory at ".$exception->getPath(); } ``` -------------------------------- ### Instantiate and Handle Request with HttpKernel in PHP Source: https://symfony.com/doc/8.0/components/http_kernel Demonstrates the core steps to initialize and use the HttpKernel component. It involves creating a Request, setting up an EventDispatcher, ControllerResolver, and ArgumentResolver, then instantiating the HttpKernel and handling the request to generate a response. ```php use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Controller\ArgumentResolver; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpKernel\HttpKernel; // create the Request object $request = Request::createFromGlobals(); $dispatcher = new EventDispatcher(); // ... add some event listeners // create your controller and argument resolvers $controllerResolver = new ControllerResolver(); $argumentResolver = new ArgumentResolver(); // instantiate the kernel $kernel = new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver); // actually execute the kernel, which turns the request into a response // by dispatching events, calling a controller, and returning the response $response = $kernel->handle($request); // send the headers and echo the content $response->send(); // trigger the kernel.terminate event $kernel->terminate($request, $response); ``` -------------------------------- ### Set and Get Session Attributes Source: https://symfony.com/doc/8.0/session Provides examples of setting a value for a session attribute and retrieving it, including providing a default value if the attribute does not exist. ```php // stores an attribute for reuse during a later user request $session->set('attribute-name', 'attribute-value'); // gets an attribute by name $foo = $session->get('foo'); // the second argument is the value returned when the attribute doesn't exist $filters = $session->get('filters', []); ``` -------------------------------- ### Create and Handle a Basic HttpKernel Request (PHP) Source: https://symfony.com/doc/8.0/components/http_kernel This example shows how to instantiate and use the HttpKernel component to handle a basic request. It involves setting up routes, a request matcher, an event dispatcher, controller and argument resolvers, and finally handling the request to send a response. ```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): Response { return new Response( sprintf("Hello %s", $request->attributes->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); ``` -------------------------------- ### Create Symfony Application with Composer (Web App) Source: https://symfony.com/doc/8.0/setup This sequence of commands uses Composer to create a new Symfony project for web applications. It first creates a skeleton project and then adds the web application extras. ```bash $ composer create-project symfony/skeleton:"8.0.*" my_project_directory $ cd my_project_directory $ composer require webapp ``` -------------------------------- ### Configure Redis Transport in messenger.yaml Source: https://symfony.com/doc/8.0/messenger Configuration for the Redis transport within the Symfony Messenger setup. This example shows how to set the DSN and customize options like the consumer name. ```yaml # config/packages/messenger.yaml framework: messenger: transports: redis: dsn: '%env(MESSENGER_TRANSPORT_DSN)%' options: consumer: '%env(MESSENGER_CONSUMER_NAME)%' ``` -------------------------------- ### Booting Symfony Kernel for Integration Tests Source: https://symfony.com/doc/8.0/testing Demonstrates how to use `KernelTestCase` to boot the Symfony application kernel for integration tests. This allows access to services within the dependency injection container. The `bootKernel()` method initializes the kernel for testing purposes. ```php namespace App\Tests\Service; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; class NewsletterGeneratorTest extends KernelTestCase { public function testSomething(): void { self::bootKernel(); // ... } } ``` -------------------------------- ### Add Flash Message Standalone Source: https://symfony.com/doc/8.0/session Illustrates how to add flash messages to a session when not using the full Symfony framework. It involves starting a session, getting the flash bag, and adding messages with a specific key. ```php use SymfonyComponentHttpFoundationSessionSession; $session = new Session(); $session->start(); // retrieve the flash messages bag $flashes = $session->getFlashBag(); // add flash messages $flashes->add( 'notice', 'Your changes were saved' ); ``` -------------------------------- ### Assert Email Attachment Count Source: https://symfony.com/doc/8.0/testing Verifies the number of attachments for a given email message. The email message needs to be retrieved first, for example, using `getMailerMessage()`. This helps ensure emails are sent with the correct attachments. ```php assertEmailAttachmentCount(RawMessage $email, int $count, string $message = '') ``` -------------------------------- ### Define Periodic Task Trigger with AsPeriodicTask Attribute Source: https://symfony.com/doc/8.0/scheduler This example demonstrates the basic usage of the AsPeriodicTask attribute to define a periodic trigger. It specifies the frequency of the task and optional start and end dates. The default behavior is to call the __invoke method of the class. ```php namespace App\Scheduler\Task; use Symfony\Component\Scheduler\Attribute\AsPeriodicTask; #[AsPeriodicTask(frequency: '1 day', from: '2022-01-01', until: '2023-06-12')] class SendDailySalesReports { public function __invoke() { // ... } } ``` -------------------------------- ### Configure Webhook Component Routing for Mailer Integration (PHP) Source: https://symfony.com/doc/8.0/webhook This PHP configuration achieves the same routing setup as the YAML example for the Webhook component. It demonstrates how to programmatically configure the DSN and route name for a mailer service, allowing the component to process webhook events. ```php use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return function (ContainerConfigurator $container) { $container->extension('framework', [ 'workflows' => [ // ... ], 'webhooks' => [ 'mailgun' => [ 'dsn' => '%env(MAILGUN_WEBHOOK_DSN)%', 'route_name' => 'app_webhook_mailgun', ], ], ]); }; ``` -------------------------------- ### Execute bin/console commands Source: https://symfony.com/doc/8.0/page_creation The bin/console command is a powerful tool for debugging, code generation, and database migrations in Symfony projects. It provides a list of available commands upon execution. ```bash php bin/console ``` -------------------------------- ### Enable and Get Profiler Data (PHP) Source: https://symfony.com/doc/8.0/testing This code demonstrates how to enable the Symfony profiler for the next request and then retrieve the collected profile data. This is useful for performance analysis, such as checking the number of database queries. It involves enabling the profiler and then accessing the returned profile object. ```php // enables the profiler for the very next request $client->enableProfiler(); $crawler = $client->request('GET', '/profiler'); // gets the profile $profile = $client->getProfile(); ``` -------------------------------- ### Simulate Browser Navigation (Back, Forward, Reload, Restart) Source: https://symfony.com/doc/8.0/testing Demonstrates basic browser navigation actions using the BrowserKit client. Includes methods for going back, forward, reloading the page, and restarting the client to clear session data. ```php $client->back(); $client->forward(); $client->reload(); // clears all cookies and the history $client->restart(); ``` -------------------------------- ### Create New Symfony Projects with Specific Versions Source: https://symfony.com/doc/8.0/setup This section shows how to create a new Symfony project specifying the desired version. You can use the 'lts' or 'next' shortcuts for Long-Term Support or upcoming versions respectively when using the Symfony CLI. For Composer, you must specify the exact version string. ```bash # use the most recent LTS version $ symfony new my_project_directory --version=lts # use the 'next' Symfony version to be released (still in development) $ symfony new my_project_directory --version=next # you can also select an exact specific Symfony version $ symfony new my_project_directory --version="6.4.*" ``` ```bash $ composer create-project symfony/skeleton:"6.4.*" my_project_directory ``` -------------------------------- ### Define Routes with Subdomain and Host Requirements (PHP) Source: https://symfony.com/doc/8.0/routing This PHP configuration achieves the same routing setup as the YAML example. It defines 'mobile_homepage' with specific subdomain requirements and defaults, and a general 'homepage' route. This uses Symfony's routing configurator for programmatic route definition. ```php // config/routes.php namespace Symfony\Component\Routing\Loader\Configurator; use App\Controller\MainController; return Routes::config([ 'mobile_homepage' => [ 'path' => '/', 'host' => '{subdomain}.example.com', 'controller' => [MainController::class, 'mobileHomepage'], 'defaults' => ['subdomain' => 'm'], 'requirements' => ['subdomain' => 'm|mobile'], ], 'homepage' => [ 'path' => '/', 'controller' => [MainController::class, 'homepage'], ], ]); ``` -------------------------------- ### Debug router with bin/console Source: https://symfony.com/doc/8.0/page_creation The 'debug:router' command within bin/console lists all defined routes in the Symfony application, displaying their names, methods, and paths. This is useful for understanding application routing. ```bash php bin/console debug:router ``` -------------------------------- ### Get Current User Object in Controller (PHP) Source: https://symfony.com/doc/8.0/security This PHP code example shows how to access the currently authenticated user object within a Symfony controller. It uses the `$this->getUser()` shortcut after ensuring the user is authenticated and demonstrates how to retrieve user properties like 'firstName'. ```php use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; class ProfileController extends AbstractController { public function index(): Response { // usually you'll want to make sure the user is authenticated first, // see "Authorization" below $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); // returns your User object, or null if the user is not authenticated // use inline documentation to tell your editor your exact User class /** @var \App\Entity\User $user */ $user = $this->getUser(); // Call whatever methods you've added to your User class // For example, if you added a getFirstName() method, you can use that. return new Response('Well hi there '.$user->getFirstName()); } } ``` -------------------------------- ### Access Latest Request/Response Objects (PHP) Source: https://symfony.com/doc/8.0/testing This snippet illustrates how to get objects related to the latest request and response made by the Symfony test client. It includes retrieving HttpKernel and BrowserKit request/response instances, as well as the Crawler instance. This is valuable for detailed inspection of request/response details. ```php // the HttpKernel request instance $request = $client->getRequest(); // the BrowserKit request instance $request = $client->getInternalRequest(); // the HttpKernel response instance $response = $client->getResponse(); // the BrowserKit response instance $response = $client->getInternalResponse(); // the Crawler instance $crawler = $client->getCrawler(); ``` -------------------------------- ### Install Twig templating engine Source: https://symfony.com/doc/8.0/page_creation Installs the Twig templating engine using Composer, a dependency manager for PHP. This enables the use of Twig templates for rendering HTML in Symfony applications. ```bash composer require twig ``` -------------------------------- ### Measure Partial Durations with Stopwatch Lap in PHP Source: https://symfony.com/doc/8.0/performance This example shows how to use the `lap()` method of the Stopwatch component to measure partial durations within a longer-running process. It starts an event, records laps for iterative steps, and then stops the event, providing detailed period information. ```php $this->stopwatch->start('process-data-records', 'export'); foreach ($records as $record) { // ... some code goes here $this->stopwatch->lap('process-data-records'); } $event = $this->stopwatch->stop('process-data-records'); // $event->getDuration(), $event->getMemory(), etc. // Lap information is stored as "periods" within the event: // $event->getPeriods(); // Gets the last event period: // $event->getLastPeriod(); ``` -------------------------------- ### Install WebLink Component with Composer Source: https://symfony.com/doc/8.0/web_link This command installs the Symfony WebLink component, which is necessary for managing Link HTTP headers and enabling asset preloading and resource hints. ```bash $ composer require symfony/web-link ``` -------------------------------- ### Making HTTP Requests with the Test Client in PHP Source: https://symfony.com/doc/8.0/testing This PHP code demonstrates the basic usage of the test client's `request()` method in Symfony. It shows how to make a GET request to a specific URL and receive a `Crawler` instance for response analysis. Hardcoding URLs is recommended for application tests. ```php $crawler = $client->request('GET', '/post/hello-world'); ``` -------------------------------- ### Disabling Kernel Reboot for Multiple Requests in PHP Source: https://symfony.com/doc/8.0/testing This PHP code demonstrates how to disable the automatic kernel reboot between requests in Symfony tests using `disableReboot()`. This can be useful for performance but requires manual handling of service resets if isolation is needed. The example shows how to prevent the security token and Doctrine entities from being cleared by implementing a compiler pass. ```php // src/Kernel.php namespace App; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel as BaseKernel; class Kernel extends BaseKernel implements CompilerPassInterface { use MicroKernelTrait; // ... public function process(ContainerBuilder $container): void { if ('test' === $this->environment) { // prevents the security token to be cleared $container->getDefinition('security.token_storage')->clearTag('kernel.reset'); // prevents Doctrine entities to be detached $container->getDefinition('doctrine')->clearTag('kernel.reset'); // ... } } } ``` -------------------------------- ### Install Symfony Filesystem Component Source: https://symfony.com/doc/8.0/components/filesystem Installs the Symfony Filesystem component using Composer. Ensure you include the Composer autoload file if using this component outside a Symfony application. ```bash $ composer require symfony\/filesystem ``` -------------------------------- ### Initialize MockHttpClient with a Callback for Dynamic Responses (PHP) Source: https://symfony.com/doc/8.0/http_client This example shows initializing MockHttpClient with a callback function. The callback is executed each time a request is made, allowing for dynamic generation of responses based on request details. ```PHP use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; $callback = function ($method, $url, $options): MockResponse { return new MockResponse('...'); }; $client = new MockHttpClient($callback); $response = $client->request('...'); // calls $callback to get the response ``` -------------------------------- ### Install Symfony Lock Component Source: https://symfony.com/doc/8.0/components/lock This command installs the Symfony Lock Component using Composer. Ensure you have Composer installed and are in your project directory. ```bash composer require symfony/lock ``` -------------------------------- ### Configuring HttplugClient with Default Options (PHP) Source: https://symfony.com/doc/8.0/http_client Illustrates how to set default options for HttplugClient, such as 'base_uri', using the `withOptions()` method. This simplifies making requests to a specific host by eliminating the need to repeat the base URI in every request. ```PHP use Psr\Http\Message\ResponseInterface; use Symfony\Component\HttpClient\HttplugClient; $httpClient = (new HttplugClient()) ->withOptions([ 'base_uri' => 'https://my.api.com', ]); $request = $httpClient->createRequest('GET', '/'); // ... ``` -------------------------------- ### Install ExpressionLanguage Component Source: https://symfony.com/doc/8.0/components/expression_language This command installs the ExpressionLanguage component using Composer. Ensure you have Composer installed and configured for your project. If using standalone, remember to include the Composer autoloader. ```bash $ composer require symfony/expression-language ``` -------------------------------- ### Run a Symfony Console Command Source: https://symfony.com/doc/8.0/console Shows the command-line syntax for executing a registered Symfony console command. The example uses `php bin/console` followed by the command name `app:create-user`. ```Shell $ php bin/console app:create-user ``` -------------------------------- ### Create Test Database and Schema using Console Commands Source: https://symfony.com/doc/8.0/testing Provides the Symfony Console commands to create a dedicated test database and its schema. `doctrine:database:create` initializes the database, and `doctrine:schema:create` sets up the necessary tables and columns. These commands are essential for ensuring a clean and consistent testing environment. ```bash # create the test database $ php bin/console --env=test doctrine:database:create # create the tables/columns in the test database $ php bin/console --env=test doctrine:schema:create ``` -------------------------------- ### Install Debug Bundle for Symfony Source: https://symfony.com/doc/8.0/templates This command installs the Symfony Debug Bundle, which is required for using the dump() function and other debugging utilities in Symfony applications. It should be installed as a development dependency. ```bash $ composer require --dev symfony/debug-bundle ``` -------------------------------- ### Install Symfony UID Component with Composer Source: https://symfony.com/doc/8.0/components/uid This command installs the Symfony UID component using Composer, the dependency manager for PHP. Ensure you have Composer installed and configured correctly in your project. ```bash composer require symfony/uid ``` -------------------------------- ### Using Scoped Clients in PHP Code Source: https://symfony.com/doc/8.0/http_client Demonstrates how to instantiate and use scoped HTTP clients in PHP code. It shows how to create a base client and then wrap it with ScopingHttpClient to apply specific URL scopes and default headers. ```php use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpClient\ScopingHttpClient; $client = HttpClient::create(); $client = new ScopingHttpClient($client, [ // the options defined as values apply only to the URLs matching // the regular expressions defined as keys 'https://api\.github\.com/' => [ 'headers' => [ 'Accept' => 'application/vnd.github.v3+json', 'Authorization' => 'token '.$githubToken, ], ], // ... ]); // relative URLs will use the 2nd argument as base URI and use the options of the 3rd argument $client = ScopingHttpClient::forBaseUri($client, 'https://api.github.com/', [ 'headers' => [ 'Accept' => 'application/vnd.github.v3+json', 'Authorization' => 'token '.$githubToken, ], ]); ``` -------------------------------- ### Install Twig Pack for Error Template Customization Source: https://symfony.com/doc/8.0/controller/error_pages This command installs the necessary Twig components (TwigBundle and TwigBridge) which are required for overriding default error templates using Twig. Ensure you have Composer installed. ```bash $ composer require symfony/twig-pack ```