Category Archives: Symfony
Protected: Conditional Routing in Symfony using ENV Vars
Twig\Extension
services:
app.twig.demo_extension:
class: LkBundle\Twig\Extension\AppDocsExtension
tags:
- { name: twig.extension }
<?php
namespace LkBundle\Twig\Extension;
/**
* Class AppDocsExtension
* @package LkBundle\Twig\Extension
*/
class AppDocsExtension extends \Twig_Extension
{
/**
* @return string
*/
public function getName()
{
return 'app_documentation_extension';
}
/**
* @return array|\Twig_Function[]
*/
public function getFunctions()
{
return array(
new \Twig_SimpleFunction(
'show_docs',
array($this,'ShowPagerFunction'),
array(
'is_safe' => array('html'),
'needs_environment' => true,
)
),
);
}
/**
* @param \Twig_Environment $environment
* @param $docs
* @return string
* @throws \Twig_Error_Loader
* @throws \Twig_Error_Runtime
* @throws \Twig_Error_Syntax
*/
public function ShowPagerFunction(\Twig_Environment $environment, $documentation)
{
return $environment->render('LkBundle:TwigExtension:docs.html.twig', array('documentation' => $documentation));
}
}
The Easiest Way To Debug A Symfony Application in PhpStorm
Do you know that many PHP developers do not know how to use IDEs to debug their applications ? It’s actually common practice for majority of them to search for errors by outputting variables to a console. This may sound kind of ridiculous to you if you come from .NET or Java like I do since we are used to work with powerful IDEs. Debugging without breakpoints and watchers sounds terrible and primitive 🙂
Obviously, there are good reasons behind why PHP developers don’t use IDE debuggers. I am not going to list the reasons here since this is not our topic. However, I can assure you that after working with many junior & senior PHP developers, I can conclude that the number one reason they don’t use a debugger is simply they don’t know how to set it up 🙂
Today, I am going to show a very simple way to use Xdebug, PHPStorm and Symfony in order to debug an application. PHPStorm is the best IDE I have used so far and it comes with amazing functionalities. Anyways here we go:
Run/Debug Configuration
In order to run/debug a Symfony application within PHPStorm, we need to create a new configuration under “Run/Debug Configurations”.

The new configuration will be based as a “PHP script”. The file for this script will point to “bin/console”, which is under our code directory and the arguments should be entered as “server:run”. Basically what this does is that anytime you hit run or debug under PHPStorm, it will call Symfony console with arguments “server:run”. So you don’t need to run your application from terminal anymore. It will be running under PHPStorm’s terminal 🙂
Xdebug
The configuration part is basically useless without a debugger. Therefore, we will be using Xdebug’s debugging functionality to capture what’s going on in Symfony. In order to do this, go to Languages & Frameworks > PHP > Servers under PHPStorm preferences.

Add a new server here. The host of the new server will be 127.0.0.1 and port will be 8000 and debugger should be set to Xdebug. Don’t use path mappings since this may cause problems with Symfony.
CLI Interpreter
It’s quite possible that your CLI interpreter might be completely missing or its Xdebug is not configured properly. You need to make sure that your local PHP contains Xdebug configuration.

The “information” button next to PHP executable path will output PHP info. Under PHPinfo you should be able to see the following:
xdebug.remote_autostart=1
xdebug.remote_connect_back=1
xdebug.remote_cookie_expire_time = 3600
xdebug.remote_enable = 0
xdebug.remote_host = localhost
xdebug.remote_port = 9000
xdebug.remote_handler = dbgp
If you don’t have Xdebug values here then you should either put them in a separate INI file or just add it under php.ini. A separate file is usually a recommended way to do this.
Time To Debug
So if everything is setup correctly, then simply hit the run button. This will call “bin/console” and output its contents to PHPStorm’s terminal. The local server should be accessible at http://127.0.0.1:8000.
Let’s add a breakpoint somewhere in your main controller. The breakpoint will be ignored if you don’t tell PHPStorm to start listening for PHP Debug Connections. So click on the following button and make sure PHPStorm is listening.
That’s it! The debugger should now stop at the breakpoint and you should be able to access locals.
Note: You can actually do this with Vagrant or Docker too. I can write an article if enough people are interested. Cheers 🙂
Symfony 4: Web Debug Toolbar and the Profiler!
Symfony 4: Web Debug Toolbar and the Profiler!
composer require profiler --dev
How to install FOSUserBundle with Symfony 4
FOSUserBundle is certainly the most popular bundle for Symfony to manage users.
With the last major version of Symfony (4), the organization of the code of the framework is a little different. The official documentation isn’t clear about the process to install this bundle.
Below, you will found the necessary steps to use FOSUserBundle. You can get all sources of this installation on repository sf4FOSUserBundle on github.
Installation
Installation is a process in 7 steps:
- Symfony 4 skeleton & required components installation
- Download FOSUserBundle using composer
- Create your User class
- Configure your application’s security.yml
- Configure the FOSUserBundle
- Import FOSUserBundle routing
- Update your database schema
Step 1: Symfony 4 skeleton & required components installation
Symfony 4 skeleton
The first step is the installation of the symfony skeleton to start from a clean base.
composer create-project symfony/skeleton demo
All next steps must be executed in the new created directory (aka. demo)
Doctrine
Object-Relational-Mapper to manage database
composer require doctrine
At this step you must, as suggested by installer, modifying your .env
configuration file and eventually config/packages/doctrine.yaml
. In .env
, the string to change is like:
DATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_name
You must indicate, the user, password, ip and name of the database.
Annotations
Docblock Annotations Parser used with Doctrine
composer require annotations
SwiftMailerBundle
Swiftmailer, free feature-rich PHP mailer in symfony bundle version
composer require swiftmailer-bundle
Twig
Twig, the flexible, fast, and secure template language for PHP
composer require twig
Optional : Web Server
Symfony WebServerBundle
composer require server --dev
Step 2: Download FOSUserBundle using composer
composer require friendsofsymfony/user-bundle "~2.0"
At the end of the installation you will have the following error message :
The child node “db_driver” at path “fos_user” must be configured.
Don’t panic, it’s normal, you must now, create your User class and configured FOSUserBundle.
Step 3: Create your User class
Create src/Entity/User.php
as custom user class who extend the FOSUserBundle BaseUser
class.
<?php // src/Entity/User.php namespace App\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="fos_user") */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; public function __construct() { parent::__construct(); // your own logic } }
Step 4: Configure your application’s security.yml
Modify config/packages/security.yaml
to setup FOSUserBundle security
security: encoders: FOS\UserBundle\Model\UserInterface: bcrypt role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: ROLE_ADMIN # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers providers: fos_userbundle: id: fos_user.user_provider.username firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false main: pattern: ^/ form_login: provider: fos_userbundle csrf_token_generator: security.csrf.token_manager logout: true anonymous: true # Easy way to control access for large sections of your site # Note: Only the *first* access control that matches will be used access_control: - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/admin/, role: ROLE_ADMIN }
Step 5: Configure the FOSUserBundle
Create a new file config/packages/fos_user.yaml
for the configuration of FOSUserBundle
fos_user: db_driver: orm # other valid values are 'mongodb' and 'couchdb' firewall_name: main user_class: App\Entity\User from_email: address: "vincent@vfac.fr" sender_name: "vincent@vfac.fr"
Update config/packages/framework.yaml
to add templating configuration
framework: templating: engines: ['twig', 'php']
Step 6: Import FOSUserBundle routing
Create config/routes/fos_user.yaml
fos_user: resource: "@FOSUserBundle/Resources/config/routing/all.xml"
Step 7: Update your database schema
If not already done, you must create your database
php bin/console doctrine:database:create
Update the schema with the informations from your User class entity
php bin/console doctrine:schema:update --force
At this point, all is installed and configured to use FOSUserBundle in Symfony 4. Run the following command to check if all is ok
composer update
If you don’t have any error message, you can test !
You can run the web server to test your application
php bin/console server:start
https://vfac.fr/blog/how-install-fosuserbundle-with-symfony-4
Override default templates in Symfony 4
In SF4 the template overrides must be placed in /templates/bundles/{BundleName}.