### Install the certificate authority and start HTTPS server Source: https://symfony.com/doc/current/setup/symfony_server.html Install the local certificate authority once, then start the server to use HTTPS automatically. ```bash # install the certificate authority (run this only once on your machine) $ symfony server:ca:install # now start (or restart) your server; it will use HTTPS automatically $ symfony server:start ``` -------------------------------- ### Install Tailwind Bundle and Initialize Source: https://symfony.com/bundles/TailwindBundle/current/index.html Run these two commands to install the bundle and initialize your app. The init command will ask a few questions about your setup. ```bash $ composer require symfonycasts/tailwind-bundle $ php bin/console tailwind:init ``` -------------------------------- ### Create and start a Symfony project with Composer Source: https://symfony.com/in-five-minutes Use these three commands to create a minimal Symfony application and start the local server. No installers or scaffolding wizards are needed. ```bash $ composer create-project symfony/skeleton my_project $ cd my_project $ symfony server:start ``` -------------------------------- ### package.xml section example Source: https://symfony.com/blog/jobeet-day-20-the-plugins Example of the section in a package.xml file, declaring required PHP and PEAR installer versions and a symfony dependency with minimum and maximum versions. The plugin:install task uses this information to install the best plugin version and required dependencies. ```xml 5.0.0 1.4.1 symfony pear.symfony-project.com 1.2.0 1.3.0 1.3.0 ``` -------------------------------- ### Create a basic Sass file (assets/styles/app.scss) Source: https://symfony.com/bundles/SassBundle/current/index.html Example Sass file with a variable and a body style. This is the starting point for using Sass with the bundle. ```scss /* assets/styles/app.scss */ $red: #fc030b; body { background: $red; } ``` -------------------------------- ### Create Symfony project and install dependencies Source: https://symfony.com/blog/introducing-symfony-panther-a-browser-testing-and-web-scrapping-library-for-php Commands to create a new Symfony project, add Twig, annotations, and dev dependencies, then start the PHP built-in web server. ```bash # create the new project $ composer create-project symfony/skeleton news-website $ cd news-website/ # add some dependencies $ composer require twig annotations $ composer require --dev maker tests # Run the PHP built-in web server $ php -S 127.0.0.1:8000 -t public ``` -------------------------------- ### Get incremental output from multiple processes Source: https://symfony.com/blog/new-in-symfony-2-2-process-component-enhancements Start multiple processes and retrieve their incremental output using getIncrementalOutput() and getIncrementalErrorOutput(). This example shows a loop that checks if each process is started, starts it if not, prints its incremental output, and removes it when it stops. ```php use Symfony\Component\Process\Process; $processes = array(); $processes[] = new Process('ls -lsa'); $processes[] = new Process('ps waux'); while (count($processes) > 0) { foreach ($processes as $i => $process) { if (!$process->isStarted()) { echo "Process starts\n"; $process->start(); continue; } echo $process->getIncrementalOutput(); echo $process->getIncrementalErrorOutput(); if (!$process->isRunning()) { echo "Process stopped\n"; unset($processes[$i]); } } sleep(1); } ``` -------------------------------- ### Start the local server and open browser with --open Source: https://symfony.com/doc/current/setup/symfony_server.html Starts the server and opens the URL in the browser in a single command. ```bash $ symfony server:start --open ``` -------------------------------- ### ai:store:setup command usage Source: https://symfony.com/doc/current/ai/bundles/ai-bundle.html Prepares the required infrastructure for a store (e.g., creates database tables, indexes, collections). Only works with stores implementing ManagedStoreInterface. ```bash $ php bin/console ai:store:setup # Setup the chromadb store $ php bin/console ai:store:setup ai.store.chromadb.default ``` -------------------------------- ### Install Cloudflare provider bridge Source: https://symfony.com/bundles/ux-image/current/index.html Install one of the provider bridges, for example Cloudflare. ```bash $ composer require symfony/ux-cloudflare-image ``` -------------------------------- ### Install JsonStreamer with Composer Source: https://symfony.com/json-streamer Use this command to install the symfony/json-streamer package in your PHP project. It is the required setup step before using the component. ```bash $ composer require symfony/json-streamer ``` -------------------------------- ### Create and enter the framework directory Source: https://symfony.com/doc/current/create_framework/introduction.html Commands to create a new directory named 'framework' and change into it. This is the first step in bootstrapping the project. ```bash $ mkdir framework $ cd framework ``` -------------------------------- ### YAML configuration examples showing parameter evaluation Source: https://symfony.com/doc/current/configuration/using_parameters_in_dic.html Three YAML configuration examples demonstrating how %kernel.debug% is evaluated. The first sets logging to true, the second uses the parameter which gets evaluated, and the third passes the string '%kernel.debug%' which is always considered true. ```YAML my_bundle: logging: true # true, as expected my_bundle: logging: '%kernel.debug%' # true/false (depends on 2nd argument of the Kernel class), # as expected, because %kernel.debug% inside configuration # gets evaluated before being passed to the extension my_bundle: ~ # passes the string "%kernel.debug%". # Which is always considered as true. # The Configurator does not know anything about # "%kernel.debug%" being a parameter. ``` -------------------------------- ### Install SMSC Notifier with Composer Source: https://symfony.com/packages/smsc-notifier Use Composer to install the symfony/smsc-notifier package in your PHP project. This is the required setup step before using the bridge. ```bash $ composer require symfony/smsc-notifier ``` -------------------------------- ### Show ckeditor:install help Source: https://symfony.com/bundles/FOSCKEditorBundle/current/usage/ckeditor.html Displays the command's documentation using the --help option. ```bash $ php bin/console ckeditor:install --help ``` -------------------------------- ### Install sfGuardPlugin with plugin:install Source: https://symfony.com/blog/jobeet-day-13-the-user Run this command to install the sfGuardPlugin by name. The plugin:install task requires PEAR and installs the latest stable version by default; pass the --release option to install a specific version. ```bash $ php symfony plugin:install sfGuardPlugin ``` -------------------------------- ### Install SmsboxNotifier with Composer Source: https://symfony.com/packages/smsbox-notifier Use Composer to install the symfony/smsbox-notifier package in your PHP project. This is the required setup step before using the notifier bridge. ```bash $ composer require symfony/smsbox-notifier ``` -------------------------------- ### Install a Recipe with ux:install Source: https://symfony.com/bundles/ux-toolkit/current/index.html Run the `ux:install` command with the recipe name to copy its files into your application. The command asks which kit to use, copies files, and lists required dependencies. ```bash $ php bin/console ux:install dialog ``` -------------------------------- ### Create a directory with Filesystem and Path Source: https://symfony.com/doc/current/components/filesystem.html This example shows how to use the Filesystem and Path classes. It creates a directory in the system temp directory with a random suffix, and catches IOExceptionInterface to handle errors, printing the path where the error occurred. ```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(); } ``` -------------------------------- ### Example services.yml before upgrade Source: https://symfony.com/doc/current/service_container/3.3-di-changes.html Initial service configuration with machine-name service IDs and explicit class definitions. ```yaml # app/config/services.yml services: app.github_notifier: class: AppBundle\Service\GitHubNotifier arguments: - '@app.api_client_github' markdown_transformer: class: AppBundle\Service\MarkdownTransformer app.api_client_github: class: AppBundle\Service\ApiClient arguments: - 'https://api.github.com' app.api_client_sl_connect: class: AppBundle\Service\ApiClient arguments: - 'https://connect.symfony.com/api' ``` -------------------------------- ### Install Symfony UX Dropzone with Composer Source: https://symfony.com/bundles/ux-dropzone/current/index.html Use this command to install the bundle via Composer and Symfony Flex. Ensure StimulusBundle is configured before starting. ```bash $ composer require symfony/ux-dropzone ``` -------------------------------- ### Install with Composer Source: https://symfony.com/bundles/DoctrineFixturesBundle/current/index.html Install the bundle using Composer with Symfony Flex. Run this command and the installation is complete. ```bash $ composer require --dev orm-fixtures ``` -------------------------------- ### Set up store and index documents from console Source: https://symfony.com/doc/current/ai/cookbook/ai-bundle-fast-track.html Console commands to prepare the store infrastructure and run the indexer. The first command sets up the ChromaDB store, the second indexes documents from a specified file path. ```bash $ php bin/console ai:store:setup ai.store.chromadb.knowledge_base $ php bin/console ai:store:index docs --source=/path/to/document.txt ``` -------------------------------- ### Install Symfony UX Cropper.js with Composer Source: https://symfony.com/bundles/ux-cropperjs/current/index.html Run this command to install the bundle using Composer and Symfony Flex. Ensure StimulusBundle is configured before starting. ```bash $ composer require symfony/ux-cropperjs ``` -------------------------------- ### Install WhatsApp Notifier Bridge with Composer Source: https://symfony.com/packages/whats-app-notifier Use Composer to install the symfony/whats-app-notifier package in your PHP project. This is the required setup step before using the bridge. ```bash $ composer require symfony/whats-app-notifier ``` -------------------------------- ### Extension class loadFromExtension examples Source: https://symfony.com/doc/current/configuration/using_parameters_in_dic.html Shows three calls to loadFromExtension with different configurations. The first passes true, the second passes the parameter string which gets evaluated, and the third passes no configuration, resulting in the string '%kernel.debug%' being passed. ```PHP $container->loadFromExtension('my_bundle', [ 'logging' => true, // true, as expected ] ); $container->loadFromExtension('my_bundle', [ 'logging' => "%kernel.debug%", // true/false (depends on 2nd parameter of Kernel), // as expected, because %kernel.debug% inside configuration // gets evaluated before being passed to the extension ] ); $container->loadFromExtension('my_bundle'); // passes the string "%kernel.debug%". // Which is always considered as true. // The Configurator does not know anything about // "%kernel.debug%" being a parameter. ``` -------------------------------- ### Install Symfony features with Composer require Source: https://symfony.com/in-five-minutes Install features on demand with Composer. Symfony configures them automatically. Examples include an ORM, a mailer, and a live component. ```bash $ composer require orm $ composer require mailer $ composer require symfony/ux-live-component ``` -------------------------------- ### Install a common Toolkit recipe with ux:install Source: https://symfony.com/blog/symfony-ux-3-4-0-released Installs the clipboard recipe from the common Toolkit kit. Use the --kit common option to specify the kit, and replace 'clipboard' with the desired recipe name (e.g., post-link, logout-link, closeable, tooltip). ```bash $ php bin/console ux:install clipboard --kit common ``` -------------------------------- ### setUploadDir examples Source: https://symfony.com/bundles/EasyAdminBundle/current/fields/ImageField.html Sets the directory where uploaded images are stored. Relative paths are resolved from the project root; absolute filesystem paths are used as-is. This option is required; an exception is thrown if not called. ```php // relative to your project root directory yield ImageField::new('...')->setUploadDir('public/uploads/images/'); // absolute filesystem paths are also supported yield ImageField::new('...')->setUploadDir('/mnt/data/images/'); // the property will only store the file path relative to this dir // (e.g. 'logo.png', 'venue/layout.jpg') ``` -------------------------------- ### Get a configuration parameter with getParameter() Source: https://symfony.com/doc/current/controller.html Use $this->getParameter() to retrieve any configuration parameter from a controller. The example shows getting the kernel.project_dir parameter to build a path. ```PHP // ... public function index(): Response { $contentsDir = $this->getParameter('kernel.project_dir').'/contents'; // ... } ``` -------------------------------- ### Install SendGrid Mailer Source: https://symfony.com/doc/current/components/mime.html Install the SendGrid mailer package to use SendGrid as a third-party transport. The Flex recipe adds a configuration example to your .env file. ```bash $ composer require symfony/sendgrid-mailer ``` -------------------------------- ### Install HttpClient and Serializer Source: https://symfony.com/doc/current/webhook.html Run this command to install the required packages for sending webhooks. ```bash $ composer require symfony/http-client symfony/serializer ``` -------------------------------- ### Basic example: ImageAdmin configureFormFields with help and help_html Source: https://symfony.com/bundles/SonataAdminBundle/current/cookbook/recipe_image_previews.html For single-layer admins, get the Image instance via $this->getSubject() and add a 'help' option with an tag to the 'file' field. The 'help_html' option is set to true to allow raw HTML. ```php final class ImageAdmin extends AbstractAdmin { protected function configureFormFields(FormMapper $form): void { // get the current Image instance $image = $this->getSubject(); // use $fileFormOptions so we can add other options to the field $fileFormOptions = ['required' => false]; if ($image && ($webPath = $image->getWebPath())) { // get the request so the full path to the image can be set $request = $this->getRequest(); $fullPath = $request->getBasePath().'/'.$webPath; // add a 'help' option containing the preview's img tag $fileFormOptions['help'] = ''; $fileFormOptions['help_html'] = true; } $form ->add('file', 'file', $fileFormOptions) ; } } ``` -------------------------------- ### Install Symfony AI Failover Platform with Composer Source: https://symfony.com/packages/ai-failover-platform Use Composer to install the symfony/ai-failover-platform package in your PHP project. This is the required setup step before using the package. ```bash $ composer require symfony/ai-failover-platform ``` -------------------------------- ### Basic HttpKernel setup with EventDispatcher and resolvers Source: https://symfony.com/doc/current/components/http_kernel.html Shows the minimal setup for creating and running an HttpKernel instance. It creates a Request, dispatcher, controller and argument resolvers, then handles the request and terminates. The numbered lines above the code are line references, not part of the code. ```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); ``` -------------------------------- ### Install the Symfony Serializer Pack with Composer Source: https://symfony.com/doc/current/components/serializer.html Run this command in a Symfony Flex application to install the serializer pack. The pack also installs commonly used optional dependencies; outside the framework, start with the symfony/serializer package instead. ```bash $ composer require symfony/serializer-pack ``` -------------------------------- ### Define a Live Component with Map (MapLivePlayground) Source: https://symfony.com/bundles/ux-map/current/index.html Use the ComponentWithMapTrait and implement instantiateMap() to return a Map instance. The example sets the center, fits bounds to markers, and adds two markers with info windows. ```php namespace App\Twig\Components; use Symfony\UX\LiveComponent\Attribute\AsLiveComponent; use Symfony\UX\LiveComponent\Attribute\LiveAction; use Symfony\UX\LiveComponent\DefaultActionTrait; use Symfony\UX\Map\InfoWindow; use Symfony\UX\Map\Live\ComponentWithMapTrait; use Symfony\UX\Map\Map; use Symfony\UX\Map\Marker; use Symfony\UX\Map\Point; #[AsLiveComponent] final class MapLivePlayground { use DefaultActionTrait; use ComponentWithMapTrait; protected function instantiateMap(): Map { return (new Map()) ->center(new Point(48.8566, 2.3522)) ->fitBoundsToMarkers() ->addMarker(new Marker(position: new Point(48.8566, 2.3522), title: 'Paris', infoWindow: new InfoWindow('Paris'))) ->addMarker(new Marker(position: new Point(45.75, 4.85), title: 'Lyon', infoWindow: new InfoWindow('Lyon'))) ; } } ``` -------------------------------- ### ManagedStoreInterface::setup() and drop() Source: https://symfony.com/doc/current/ai/components/store.html Defines methods to setup and drop the store, required for stores that need to create tables, indexes, etc. before storing vectors. ```APIDOC ## ManagedStoreInterface::setup() and drop() ### Description Defines methods to setup and drop the store. The setup() method creates the necessary tables, indexes, etc., while drop() removes the store and related vectors. ### Method setup() and drop() ### Signature ```php public function setup(array $options = []): void public function drop(array $options = []): void ``` ### Parameters - **$options** (array) - Optional - An associative array of options for the operation. ### Example ```php use Symfony\AI\Store\ManagedStoreInterface; use Symfony\AI\Store\StoreInterface; class MyCustomStore implements ManagedStoreInterface, StoreInterface { public function setup(array $options = []): void { // Implementation to create the store } public function drop(array $options = []): void { // Implementation to drop the store (and related vectors) } } ``` ``` -------------------------------- ### Get timezone offsets with Timezones::getRawOffset() and getGmtOffset() Source: https://symfony.com/blog/new-in-symfony-4-3-timezone-improvements Use Timezones::getRawOffset() to get the raw offset in seconds from UTC, and Timezones::getGmtOffset() to get the offset as a GMT string. Examples show results for Etc/UTC, America/Buenos_Aires, and Asia/Katmandu. ```php $offset = Timezones::getRawOffset('Etc/UTC'); // $offset = 0 $offset = Timezones::getRawOffset('America/Buenos_Aires'); // $offset = -10800 $offset = Timezones::getRawOffset('Asia/Katmandu'); // $offset = 20700 $offset = Timezones::getGmtOffset('Etc/UTC'); // $offset = 'GMT+00:00' $offset = Timezones::getGmtOffset('America/Buenos_Aires'); // $offset = 'GMT-03:00' $offset = Timezones::getGmtOffset('Asia/Katmandu'); // $offset = 'GMT+05:45' ``` -------------------------------- ### Write Agent Instructions in INSTRUCTIONS.md Source: https://symfony.com/doc/current/ai/components/mate/creating-extensions.html Example `INSTRUCTIONS.md` file that maps existing CLI commands to Mate tools and states the benefits. It shows how to structure the instructions to tell an agent when to use your tools, including a table of command replacements and a list of benefits. ```markdown ## My Extension Use the Mate tools instead of the CLI for better results: | Instead of... | Use | |----------------------------|--------------------------------------------------------| | `my-cli command` | `vendor/bin/mate tools:call my-tool` | | `my-cli search "term"` | `vendor/bin/mate tools:call my-search --term="term"` | ### Benefits - Structured output that AI can parse - Better error handling and context - Integrated with project configuration ``` -------------------------------- ### Install Symfony 2.3.0 with Composer Source: https://symfony.com/blog/upgrading-your-symfony-projects-the-easy-way Use this command to install Symfony 2.3.0 via Composer. It is the only explicit code example in the source and is used to demonstrate the upgrade process. ```bash composer create-project symfony/framework-standard-edition . 2.3.0 ``` -------------------------------- ### Download and extract example templates Source: https://symfony.com/doc/current/the-fast-track/en/22-styling.html Run these commands to download and extract the example templates archive at the project root. The archive contains templates that demonstrate Twig tricks. ```bash $ php -r "copy('https://symfony.com/uploads/assets/guestbook-8.1.zip', 'guestbook-8.1.zip');" $ unzip -o guestbook-8.1.zip $ rm guestbook-8.1.zip ``` -------------------------------- ### Install and verify a Mate extension Source: https://symfony.com/doc/current/ai/components/mate/creating-extensions.html Installs the extension and verifies its capabilities. In a project that ran mate init, the Composer plugin runs mate discover automatically. ```bash $ composer require --dev vendor/my-extension $ vendor/bin/mate debug:capabilities --extension=vendor/my-extension ``` -------------------------------- ### Install Vonage Notifier with Composer Source: https://symfony.com/packages/vonage-notifier Use Composer to install the symfony/vonage-notifier package in your PHP project. This is the required setup step before using the Vonage SMS notifier bridge. ```bash $ composer require symfony/vonage-notifier ``` -------------------------------- ### Install Symfony Slack Notifier with Composer Source: https://symfony.com/packages/slack-notifier Use Composer to install the symfony/slack-notifier package in your PHP project. This is the required setup step before using the Slack notifier bridge. ```bash $ composer require symfony/slack-notifier ``` -------------------------------- ### Install a Recipe with a Specific Kit Source: https://symfony.com/bundles/ux-toolkit/current/index.html Use the `--kit` option to skip the kit selection question and directly install a recipe from a specified kit, such as `shadcn`. ```bash $ php bin/console ux:install button --kit=shadcn ``` -------------------------------- ### Install vue-loader and run watch Source: https://symfony.com/bundles/ux-vue/current/index.html Install the Vue loader with npm and start the watch mode. The --force flag is required to override potential peer dependency conflicts. ```bash $ npm install -D vue-loader --force $ npm run watch ``` -------------------------------- ### Basic usage example with Vertex AI Source: https://symfony.com/doc/current/ai/components/platform/vertexai.html Create a platform instance using the Factory, build a message bag, and invoke a Gemini model. Uses environment variables for location and project. ```php use Symfony\AI\Platform\Bridge\VertexAi\Factory; use Symfony\AI\Platform\Message\Message; use Symfony\AI\Platform\Message\MessageBag; $platform = Factory::createPlatform( $_ENV['GOOGLE_CLOUD_LOCATION'], $_ENV['GOOGLE_CLOUD_PROJECT'], httpClient: $httpClient ); $messages = new MessageBag( Message::ofUser('Hello, how are you?') ); $result = $platform->invoke('gemini-2.5-flash', $messages); echo $result->asText(); ``` -------------------------------- ### Install Supervisor on Ubuntu Source: https://symfony.com/doc/current/components/messenger.html Install Supervisor on Ubuntu using apt-get. ```bash $ sudo apt-get install supervisor ``` -------------------------------- ### Get country code from timezone ID Source: https://symfony.com/doc/current/components/intl.html Uses Timezones::getCountryCode() to get the country code for a given timezone ID. The example shows 'America/Vancouver' returning 'CA' for Canada. ```php $countryCode = Timezones::getCountryCode('America/Vancouver'); // => $countryCode = 'CA' (CA = Canada) ``` -------------------------------- ### Show make:controller help Source: https://symfony.com/bundles/SymfonyMakerBundle/current/index.html Displays the help for the make:controller command, including its optional arguments and options. ```bash $ php bin/console make:controller --help ``` -------------------------------- ### Install Symfony Telegram Notifier via Composer Source: https://symfony.com/packages/telegram-notifier Use Composer to install the symfony/telegram-notifier package in your PHP project. This is the required setup step before using the Telegram notifier bridge. ```bash $ composer require symfony/telegram-notifier ``` -------------------------------- ### Enable multiple server tools simultaneously Source: https://symfony.com/doc/current/ai/components/platform/gemini-server-tools.html Shows how to enable multiple server tools at once: URL Context, Google Search, and Code Execution. The example asks to calculate the factorial of 20 and show the code. Uses 'server_tools' with all three options set to true. ```php $messages = new MessageBag( Message::ofUser('Calculate the factorial of 20 and show me the code') ); $result = $platform->invoke('gemini-2.5-pro', $messages, [ 'server_tools' => [ 'url_context' => true, 'google_search' => true, 'code_execution' => true, ] ]); ``` -------------------------------- ### Install Symfony Mailgun Mailer Bridge with Composer Source: https://symfony.com/packages/mailgun-mailer Use Composer to install the symfony/mailgun-mailer package in your PHP project. This is the required setup step before using the Mailgun mailer bridge. ```bash $ composer require symfony/mailgun-mailer ``` -------------------------------- ### Implement ManagedStoreInterface with setup and drop methods Source: https://symfony.com/doc/current/ai/components/chat.html Create a custom store that requires setup and drop operations by implementing both ManagedStoreInterface and MessageStoreInterface. The setup method creates the store, and the drop method removes the store and related messages. ```php use Symfony\AI\Chat\ManagedStoreInterface; use Symfony\AI\Chat\MessageStoreInterface; class MyCustomStore implements ManagedStoreInterface, MessageStoreInterface { # ... public function setup(array $options = []): void { // Implementation to create the store } public function drop(): void { // Implementation to drop the store (and related messages) } } ``` -------------------------------- ### Get GMT offset in a specific locale Source: https://symfony.com/doc/current/components/intl.html Passes a locale as the third argument to getGmtOffset() to get the offset string in that locale. The example shows Arabic ('ar') and Dzongkha ('dz') translations. ```php $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 28, 2019'), 'ar'); // $offset = 'غرينتش+01:00' $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 28, 2019'), 'dz'); // $offset = 'ཇི་ཨེམ་ཏི་+01:00' ``` -------------------------------- ### Install Mate skills Source: https://symfony.com/blog/symfony-ai-spotlight-mate-an-agent-s-way-into-your-runtime Ensure you have run the install command to install the skills into your project's AGENTS.md. The first block appears to be a placeholder or incomplete line, but the second is the actual command to run. ```text 1 ``` ```bash $ vendor/bin/mate skills:install ``` -------------------------------- ### Get Script Names with Scripts::getNames() Source: https://symfony.com/doc/current/components/intl.html Retrieve script names using the Scripts class. The example shows getting all names and a single name, with comments showing expected output. ```php use Symfony\Component\Intl\Scripts; \Locale::setDefault('en'); $scripts = Scripts::getNames(); // ('scriptCode' => 'scriptName') // => ['Adlm' => 'Adlam', 'Afak' => 'Afaka', ...] $script = Scripts::getName('Hans'); // => 'Simplified' ``` -------------------------------- ### Check process status and restart if needed Source: https://symfony.com/blog/new-in-symfony-2-2-process-component-enhancements Use the new status methods isStarted() and isTerminated() to determine if a process has started or terminated. This example shows how to restart a process that has started but is not successful. ```php $process->isSuccessful(); $process->hasBeenSignaled(); $process->hasBeenStopped(); $process->isRunning(); // new in 2.2 $process->isStarted(); $process->isTerminated(); if (!$process->isRunning()) { if ($process->isStarted() && !$process->isSuccessful()) { $cloned = $process->restart(); // ... } } ``` -------------------------------- ### Start a web server in the foreground with bin/console server:run Source: https://symfony.com/blog/new-in-symfony-3-3-webserverbundle Starts the built-in PHP web server in the foreground and displays the logs. Use this command for local development when you want to see request logs directly in the terminal. ```bash # start a web server in the foreground and see the logs $ bin/console server:run ``` -------------------------------- ### Select image and get Image object Source: https://symfony.com/doc/current/components/dom_crawler.html Use `selectImage()` to find an image by its `alt` attribute, then call `image()` to get the `Image` object. The example shows selecting an image with alt text 'Kitten' and getting the image object directly in one line. ```php $imagesCrawler = $crawler->selectImage('Kitten'); $image = $imagesCrawler->image(); // or do this all at once $image = $crawler->selectImage('Kitten')->image(); ``` -------------------------------- ### FlysystemLoader dependencies and setup Source: https://symfony.com/bundles/LiipImagineBundle/current/data-loader/flysystem.html The FlysystemLoader uses a League\Flysystem\Filesystem instance to load files from any source supported by Flysystem. The league/flysystem package provides Flysystem, and the easiest way to set up a service is via OneupFlysystemBundle or The League FlysystemBundle, both of which let you define filesystems as services. ```text The `FlysystemLoader` lets you load images using the Flysystem filesystem abstraction layer. ``` -------------------------------- ### Example manifest.json output Source: https://symfony.com/doc/current/frontend/encore/versioning.html Example of the manifest.json file generated by Encore. It maps original asset paths to versioned filenames. This file is needed to get the versioned filename of other files like fonts or images. ```json { "build/app.js": "/build/app.123abc.js", "build/dashboard.css": "/build/dashboard.a4bf2d.css", "build/images/logo.png": "/build/images/logo.3eed42.png" } ``` -------------------------------- ### Complete example: UserController implementation Source: https://symfony.com/bundles/NelmioApiDocBundle/current/symfony_attributes.html A controller demonstrating the usage of MapQueryString, MapQueryParameter, MapRequestPayload, and MapUploadedFile with OpenAPI attributes. ```php namespace AppBundle\Controller; use AppBundle\UserDTO; use AppBundle\UserQuery; use OpenApi\Attributes as OA; use Symfony\Component\HttpKernel\Attribute\MapQueryParameter; use Symfony\Component\HttpKernel\Attribute\MapQueryString; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; use Symfony\Component\HttpKernel\Attribute\MapUploadedFile; use Symfony\Component\Routing\Attribute\Route; class UserController { /** * Find user with MapQueryString. */ #[Route('/api/users', methods: ['GET'])] #[OA\Parameter( name: 'userId', description: 'Id of the user to find', in: 'query', )] public function findUser(#[MapQueryString] UserQuery $userQuery) { // ... } /** * Find user with MapQueryParameter. */ #[Route('/api/users/v2', methods: ['GET'])] #[OA\Parameter( name: 'userId', description: 'Id of the user to find', in: 'query', )] public function findUserV2(#[MapQueryParameter] int $userId) { // ... } /** * Create a new user. */ #[Route('/api/users', methods: ['POST'])] #[OA\RequestBody( groups: ['create'], )] public function createUser(#[MapRequestPayload] UserDTO $user) { // ... } /** * Upload a profile picture */ #[Route('/api/users/picture', methods: ['POST'])] #[OA\RequestBody( description: 'Content of the profile picture upload request', content: [ new OA\MediaType('multipart/form-data', new OA\Schema( properties: [new OA\Property( property: 'file', description: 'File containing the profile picture', )], )), ], )] public function createUser(#[MapUploadedFile] UploadedFile $picture) { // ... } } ``` -------------------------------- ### Common DSN examples for RedisAdapter::createConnection() Source: https://symfony.com/doc/current/cache/adapters/redis_adapter.html Shows various valid DSNs combining host, port, database index, authentication, and multiple servers. Includes alternate syntax and auth parameters. ```php use Symfony\Component\Cache\Adapter\RedisAdapter; // host "my.server.com" and port "6379" RedisAdapter::createConnection('redis://my.server.com:6379'); // host "my.server.com" and port "6379" and database index "20" RedisAdapter::createConnection('redis://my.server.com:6379/20'); // host "localhost", auth "abcdef" and timeout 5 seconds RedisAdapter::createConnection('redis://abcdef@localhost?timeout=5'); // socket "/var/run/redis.sock" and auth "bad-pass" RedisAdapter::createConnection('redis://bad-pass@/var/run/redis.sock'); // host "redis1" (docker container) with alternate DSN syntax and selecting database index "3" RedisAdapter::createConnection('redis:?host[redis1:6379]&dbindex=3'); // providing credentials with alternate DSN syntax RedisAdapter::createConnection('redis:myusername:verysecurepassword@?host[redis1:6379]&dbindex=3'); // providing credentials with auth parameters RedisAdapter::createConnection('redis://host?auth[]=myusername&auth[]=verysecurepassword'); // a single DSN can also define multiple servers RedisAdapter::createConnection( 'redis:?host[localhost]&host[localhost:6379]&host[/var/run/redis.sock:]&auth=my-password&redis_cluster=1' ); ``` -------------------------------- ### Get timezones for a country code Source: https://symfony.com/doc/current/components/intl.html Uses Timezones::forCountryCode() to get an array of timezone IDs for a given country code (uppercase). The example shows Chile ('CL') returning three timezone IDs. ```php // unlike language codes, country codes are always uppercase (CL = Chile) $timezones = Timezones::forCountryCode('CL'); // => ['America/Punta_Arenas', 'America/Santiago', 'Pacific/Easter'] ``` -------------------------------- ### Create and render a table with Table helper Source: https://symfony.com/doc/current/components/console/helpers/table.html Use the Table helper to display tabular data. Instantiate Table with the OutputInterface, set headers and rows, then call render(). The example uses the AsCommand attribute and returns Command::SUCCESS. ```php use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Output\OutputInterface; // ... #[AsCommand(name: 'app:my-command')] class MyCommand { public function __invoke(OutputInterface $output): int { $table = new Table($output); $table ->setHeaders(['ISBN', 'Title', 'Author']) ->setRows([ ['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'], ['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'], ['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'], ['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'], ]) ; $table->render(); return Command::SUCCESS; } } ``` ```text +---------------+--------------------------+------------------+ | ISBN | Title | Author | +---------------+--------------------------+------------------+ | 99921-58-10-7 | Divine Comedy | Dante Alighieri | | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien | | 80-902734-1-6 | And Then There Were None | Agatha Christie | +---------------+--------------------------+------------------+ ``` -------------------------------- ### Get timezone offsets with a timestamp for DST Source: https://symfony.com/doc/current/components/intl.html Demonstrates passing a timestamp as the second argument to getRawOffset() and getGmtOffset() to get the offset at a specific point in time, accounting for DST changes. The example uses Madrid in 2019. ```php // In 2019, the DST period in Madrid (Spain) went from March 31 to October 27 $offset = Timezones::getRawOffset('Europe/Madrid', strtotime('March 31, 2019')); // $offset = 3600 $offset = Timezones::getRawOffset('Europe/Madrid', strtotime('April 1, 2019')); // $offset = 7200 $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 27, 2019')); // $offset = 'GMT+02:00' $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 28, 2019')); // $offset = 'GMT+01:00' ``` -------------------------------- ### Install the bundle with Composer Source: https://symfony.com/bundles/LexikJWTAuthenticationBundle/current/index.html Run this command to add the lexik/jwt-authentication-bundle package to your project. ```bash $ php composer.phar require "lexik/jwt-authentication-bundle" ``` -------------------------------- ### Get route name and parameters in a controller Source: https://symfony.com/doc/current/console/request_context.html Use the Request object in a controller to retrieve the current route name and parameters from request attributes. The example also shows how to get all attributes. The route is defined with the `#[Route]` attribute. ```php // src/Controller/BlogController.php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; class BlogController extends AbstractController { #[Route('/blog', name: 'blog_list')] public function list(Request $request): Response { $routeName = $request->attributes->get('_route'); $routeParameters = $request->attributes->get('_route_params'); // use this to get all the available attributes (not only routing ones): $allAttributes = $request->attributes->all(); // ... } } ``` -------------------------------- ### Select links and get Link object Source: https://symfony.com/doc/current/components/dom_crawler.html Use `filter()` to find links by id or class, and `selectLink()` to find links by content. Both return a `Crawler` instance; call `link()` to get the `Link` object. The example shows selecting by id, class, and content, then getting the link directly in one line. ```php // first, select the link by id, class or content... $linkCrawler = $crawler->filter('#sign-up'); $linkCrawler = $crawler->filter('.user-profile'); $linkCrawler = $crawler->selectLink('Log in'); // ...then, get the Link object: $link = $linkCrawler->link(); // or do all this at once: $link = $crawler->filter('#sign-up')->link(); $link = $crawler->filter('.user-profile')->link(); $link = $crawler->selectLink('Log in')->link(); ``` -------------------------------- ### Setup MongoDB Store Source: https://symfony.com/doc/current/ai/components/store/mongodb.html Call setup() to create the collection and its Atlas Vector Search index. If either already exists, the call is a no-op and existing resources are preserved. ```php $store->setup(); ``` -------------------------------- ### Install OneupFlysystemBundle with Composer Source: https://symfony.com/bundles/LiipImagineBundle/current/cache-resolver/flysystem.html Run this command to install the OneupFlysystemBundle, which provides a service for Flysystem filesystems. ```bash $ composer require oneup/flysystem-bundle ``` -------------------------------- ### Mailer class with options array Source: https://symfony.com/doc/current/components/options_resolver.html Initial Mailer class that stores options in an array, used as the starting point for the examples. ```php class Mailer { protected array $options; public function __construct(array $options = []) { $this->options = $options; } } ``` -------------------------------- ### Create Author entity class Source: https://symfony.com/doc/current/validation.html Initial Author class with a private $name property, used as the starting point for validation examples. ```php // src/Entity/Author.php namespace App\Entity; class Author { private string $name; } ``` -------------------------------- ### PHP service configuration example Source: https://symfony.com/doc/current/components/dependency_injection/index.html Example of a services.php file using the Configurator to define parameters and services with arguments referencing other services. ```php // services.php namespace Symfony\Component\DependencyInjection\Loader\Configurator; use App\Formatter\TextFormatter; use App\Service\MessageGenerator; return App::config([ 'parameters' => [ 'app.locale' => 'es', ], 'services' => [ 'app.text_formatter' => [ 'class' => TextFormatter::class, ], 'app.message_generator' => [ 'class' => MessageGenerator::class, 'arguments' => [service('app.text_formatter')], ], ], ]); ``` -------------------------------- ### Security Voter Example in Symfony 2.6 Source: https://symfony.com/blog/new-in-symfony-2-6-simpler-security-voters Example of a security voter class in Symfony 2.6. The code is not fully shown in the source; only the class declaration and method signature are visible. Use this as a starting point for implementing custom authorization logic with voters. ```php class PostVoter extends Voter { protected function supports($attribute, $subject) { // ... } protected function voteOnAttribute($attribute, $subject, TokenInterface $token) { // ... } } ``` -------------------------------- ### Start the local web server with symfony server:start Source: https://symfony.com/doc/current/setup/symfony_server.html Serve a Symfony project locally. The command blocks the terminal and outputs the server URL. Use --open to open the browser automatically. ```bash $ cd my-project/ $ symfony server:start [OK] Web server listening on http://127.0.0.1:8000 ... ``` -------------------------------- ### Get transport name from WorkerMetadata in WorkerRunningEvent listener Source: https://symfony.com/blog/new-in-symfony-5-4-messenger-improvements Use $event->getWorker()->getWorkerMetadata()->getTransportName() inside a listener handling WorkerRunningEvent to get the actual transport name. The example checks if the worker is idle and if the transport is in the receivers list before resetting services. ```php public function resetServices(WorkerRunningEvent $event): void { $actualTransportName = $event->getWorker()->getWorkerMetadata()->getTransportName(); if (!$event->isWorkerIdle() || !in_array($actualTransportName, $this->receiversName, true)) { return; } $this->servicesResetter->reset(); } ``` -------------------------------- ### PhpStanExtractor usage with example class Source: https://symfony.com/doc/current/components/property_info.html Shows a Foo class with a constructor property and how to use PhpStanExtractor to get type and description information from annotations. ```php // src/Domain/Foo.php class Foo { /** * @param string $bar */ public function __construct( private string $bar, ) { } } // Extraction.php use Symfony\Component\PropertyInfo\Extractor\PhpStanExtractor; use App\Domain\Foo; $phpStanExtractor = new PhpStanExtractor(); // Type information. $phpStanExtractor->getTypeFromConstructor(Foo::class, 'bar'); // Description information. $phpStanExtractor->getShortDescription($class, 'bar'); $phpStanExtractor->getLongDescription($class, 'bar'); ``` -------------------------------- ### Setup with Extra Index Fields Source: https://symfony.com/doc/current/ai/components/store/mongodb.html Pass additional field definitions to setup() to include extra fields in the search index. Each field requires a path and type. ```php $store->setup([ 'fields' => [ [ 'path' => 'title', 'type' => 'string', ], ], ]); ``` -------------------------------- ### Install LiipImagineBundle with Composer Source: https://symfony.com/bundles/LiipImagineBundle/current/installation.html Run this command in your project directory to download the latest stable version of the bundle and add it as a dependency. If you accept the Symfony Flex recipe, the bundle is registered, routing is set up, and a configuration skeleton file is created. ```bash composer require liip/imagine-bundle ``` -------------------------------- ### Use pagination component in Twig template Source: https://symfony.com/bundles/ux-pagination/current/installation.html Twig template example using the component. Requires TwigComponent to be installed. ```twig {# templates/product/index.html.twig #} ``` -------------------------------- ### Command execution output example Source: https://symfony.com/doc/current/components/console/helpers/index.html Example of executing the command and the resulting console output. ```bash $ php bin/console app:create-user User Creator ============ Whoa! You are about to create a user. ``` -------------------------------- ### Configure asset_mapper.paths with namespaces Source: https://symfony.com/doc/current/frontend/asset_mapper.html Assigns a namespace to a path, prefixing the logical path of files in that directory. For example, files in 'vendor/some/package/assets/' get prefixed with 'some-package'. ```yaml framework: asset_mapper: paths: assets/: '' vendor/some/package/assets/: 'some-package' ``` -------------------------------- ### Setup with TemplateRendererListener Source: https://symfony.com/doc/current/ai/components/platform.html Registers the TemplateRendererListener with the event dispatcher and creates a platform instance with the listener. ```php use Symfony\AI\Platform\EventListener\TemplateRendererListener; use Symfony\AI\Platform\Message\TemplateRenderer\StringTemplateRenderer; use Symfony\AI\Platform\Message\TemplateRenderer\TemplateRendererRegistry; use Symfony\Component\EventDispatcher\EventDispatcher; $eventDispatcher = new EventDispatcher(); $rendererRegistry = new TemplateRendererRegistry([ new StringTemplateRenderer(), ]); $templateListener = new TemplateRendererListener($rendererRegistry); $eventDispatcher->addSubscriber($templateListener); $platform = Factory::createPlatform($apiKey, eventDispatcher: $eventDispatcher); ``` -------------------------------- ### YAML service configuration example Source: https://symfony.com/doc/current/components/dependency_injection/index.html Example of a services.yaml file defining parameters and services with arguments referencing other services. ```yaml # services.yaml parameters: app.locale: 'es' services: app.text_formatter: class: App\Formatter\TextFormatter app.message_generator: class: App\Service\MessageGenerator arguments: ['@app.text_formatter'] ``` -------------------------------- ### Install API Platform Source: https://symfony.com/doc/current/mercure.html Installs the API Platform library using its official recipe. ```bash $ composer require api ```