Category Archives: Symfony

Symfony 4/5 Password Reset

Here I’m sharing how to reset the password of a user in symfony 4.



namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

class UserPasswordResetType extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options)
            ->add('plainPassword', RepeatedType::class, array(
                'type' => PasswordType::class,
                'first_options' => array('label' => 'New Password'),
                'second_options' => array('label' => 'Repeat New Password')

    public function configureOptions(OptionsResolver $resolver)
            'data_class' => User::class,


{% extends "base.html.twig" %}

{% block body %}
    {{ form_start(form) }}
    {{ form_label(form.plainPassword.first) }}
    {{ form_widget(form.plainPassword.first) }}
    {{ form_label(form.plainPassword.second) }}
    {{ form_widget(form.plainPassword.second) }}
    <input type="submit" value="Submit">

    {{ form_end(form) }}
{% endblock %}


public function resetPassword(Request $request, User $user, UserPasswordEncoderInterface $passwordEncoder): Response
        $form = $this->createForm(UserPasswordResetType::class, $user);

        if ($form->isSubmitted() && $form->isValid()) {
            // encode the plain password

            $entityManager = $this->getDoctrine()->getManager();

            $this->addFlash('success', "Password reset successfully");
            return $this->redirectToRoute('your_redirect_path');

        return $this->render('reset-password.html.twig', [
            'user' => $user,
            'form' => $form->createView(),

If you need password change feature simply add field for old password in form and verify old password before resetting to new password.


Nepals Popular Payment Gateway eSewa Integration – Symfony 3 Example

Here today I’m going to post a piece of code to integrate Nepal’s one of popular payment gateway eSewa.

* Created by PhpStorm.
* User: bhaktaraz
* Date: 6/13/18
* Time: 2:47 PM
namespace Fundprabhu\Bundle\PaymentBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Fundprabhu\Bundle\MainBundle\Entity\Donation;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class EsewaController extends Controller
public function redirectAction(Request $request)
$donationId = $request->get('donation_id');
$donation = $this->getDoctrine()->getRepository(Donation::class)->find($donationId);
$amt = $donation->getAmount();
$txAmt = 0;
$psc = 0;
$pdc = 0;
$tAmt = $amt + $txAmt + $psc + $pdc;
$pid = $donation->getId();
$data['donation'] = $donation;
$data['tAmt'] = $tAmt;
$data['pid'] = $pid;
return $this->render('FundprabhuPaymentBundle:Esewa:redirect.html.twig', $data);
public function successAction(Request $request)
$oid = $request->get('oid');
$pid = $oid;
$rid = $request->get('refId');
$amt = $request->get('amt');
$esewaUrl = $this->container->getParameter('esewa_tra_veryfy_url');
$scd = $this->container->getParameter('esewa_service_code');
$url = $esewaUrl . '?' . 'rid=' . $rid . '&pid=' . $pid . '&amt=' . $amt . '&scd=' . $scd;
$em = $this->getDoctrine()->getManager();
$donationId = $this->get('session')->get('donation_id');
$donation = $em->getRepository(Donation::class)->find($donationId);
//verify transaction
if ($this->transactionVerify($url)) {
'You have successfully donated for campaign ' . $donation->getCampaign()->getTitle());
} else {
'Unable to make donation for campaign ' . $donation->getCampaign()->getTitle());
return $this->redirectToRoute('fundprabhu_web_user_donations');
public function failureAction()
$em = $this->getDoctrine()->getManager();
$donationId = $this->get('session')->get('donation_id');
$donation = $em->getRepository(Donation::class)->find($donationId);
$em = $this->getDoctrine()->getManager();
'Unable to make donation for campaign ' . $donation->getCampaign()->getTitle());
return $this->redirectToRoute('fundprabhu_web_user_donations');
private function transactionVerify($url)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$dom = new \DOMDocument();
$result = simplexml_import_dom($dom);
if (trim($result[0]->response_code) == 'Success') {
return true;
return false;

view raw
hosted with ❤ by GitHub

<div style="display: none;">
<form action="{{ esewa_payment_url }}" method="POST" target="_parent" name="esewa">
<input value="{{ tAmt }}" name="tAmt" type="hidden">
<input value="{{ tAmt }}" name="amt" type="hidden">
<input value="0" name="txAmt" type="hidden">
<input value="0" name="psc" type="hidden">
<input value="0" name="pdc" type="hidden">
<input value="{{ esewa_service_code }}" name="scd" type="hidden">
<input value="{{ pid }}" name="pid" type="hidden">
<input value="{{ esewa_success_url }}" type="hidden" name="su">
<input value="{{ esewa_failure_url }}" type="hidden"
<input value="Continue to Payment" type="submit" style="border-radius:8px; background:#3C0; font-size:20px; color:#fff; font-weight:bold; padding:6px; width:60%;">
window.onload = function () {

view raw
hosted with ❤ by GitHub

Symfony – Manipulating Database Sessions

The default Symfony session storage writes the session information to files. Most medium to large websites use a database to store the session values instead of files, because databases are easier to use and scale in a multiple web server environment.

Symfony has a built-in solution for database session storage called PdoSessionHandler.

You can read the article here to Use PdoSessionHandler to Store Sessions in the Database Here.


AccessUsers in Session Data

You can also decode, access and modify user session data easily, since it’s now stored in the database. This means you could get stats from logged in users, queue notifications for users, check certain types of history.. stuff like that.

Here’s an example command which prints out a list and count of users who have been active in the last 10 minutes:


// src/Your/Bundle/Command/SessionsCheckCommand.php
namespace Your\Bundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SessionsCheckCommand extends ContainerAwareCommand
    protected function configure()
          ->setDescription('Checks user activity for the past couple of minutes and prints out some stats');

    protected function execute(InputInterface $input, OutputInterface $output)
        $threshold = 600; // Maximum seconds for last activity
        $limit = time() - $threshold;

        $em = $this->getContainer()->get('doctrine.orm.entity_manager');

        $dql = 'select s from YourBundle:Session s
            where s.sessionTime >= ?1
            order by s.sessionTime desc';
        $query = $em->createQuery($dql);
        $query->setParameter(1, $limit);
        $sessions = $query->getResult();

        $active_users = array();                // Names of active users
        $total_active_count = count($sessions); // Total active users
        $total_active_auth_count = 0;           // Total active logged in users

        foreach ($sessions as $session) {
            $data =$session->getSessionValue();
            $data = str_replace('_sf2_attributes|', '', $data);
            $data = unserialize($data);

            // If this is a session belonging to an anonymous user, do nothing
            if (!array_key_exists('_security_main', $data)) continue;

            // User is logged in, increment counter

            // Grab security data
            $data = $data['_security_main'];
            $data = unserialize($data);

            // Add username to activity list
            $active_users[] = $data->getUser()->getUsername();

        $output->writeln('The following users were active in the past few minutes:');
        $output->writeln(join(', ', $active_users));

            '%s user(s) were active, and %s of them was/were logged in.',

Caching Data in Symfony2

It is not too easy to enhance the performance of your application. In Symfony2 you could get benefit from caching. The most effective way to improve performance of an application is to cache the full output of a page and then bypass the application entirely on each subsequent request. The cache is the “middle-man” of the request-response communication between the client and your application. Caching data in Symfony2 with doctrine cache bundle can be implemented as described below.

Installing this bundle can be done through these simple steps:

1. Add this bundle to your project as a composer dependency:

// composer.json
    // ...
    require: {
        // ...
        "doctrine/doctrine-cache-bundle": "~1.0"

2. Add this bundle in your application kernel:

// application/ApplicationKernel.php
public function registerBundles()
    // ...
    $bundles[] = new \Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle();

    return $bundles;


Simply use doctrine_cache.providers.{provider_name} to inject it into the desired service.

Check the following sample:

$apcCache = $this->container->get('doctrine_cache.providers.my_apc_cache');
$arrayCache = $this->container->get('doctrine_cache.providers.my_array_cache');

Usage Example for MongoDb:

In Your Config File

// config.yml

        cache_categories: classifiad_category_cache
                server: mongodb://%mongodb_host%:%mongodb_port%
                database_name: %mongodb_database%

In Your Controller

// Saving Cached Data
$CategoryCacheProvider = $this->container->get('doctrine_cache.providers.classifiad_category_cache');
$CategoryCacheProvider->save('cache_categories', $categories, 60 * 60);

// Fetching Cached Data
$CategoryCacheProvider = $this->container->get('doctrine_cache.providers.classifiad_category_cache');
if ($CategoryCacheProvider->fetch('cache_categories')) {
    $categories = $CategoryCacheProvider->fetch('cache_categories');

Awesome Symfony2 Bundles

A list of awesome Symfony 2 bundles, utilities and resources.

User Management

* FOSUserBundle – Adds support for a database-backed user system.
* HWIOAuthBundle – OAuth client integration. Supports both OAuth1.0a and OAuth2.
* JMSSecurityExtraBundle – Enhances the Security Component with several new features.

Web Services

* FOSRestBundle – Provides various tools to rapidly develop RESTful API’s & applications.
* FOSOAuthServerBundle – A server side OAuth2 bundle.
* JMSSerializerBundle – Easily serialize, and deserialize data of any complexity.
* NelmioApiDocBundle – Generates documentation for your REST API from annotations.
* RequestLimitBundle – With this bundle you can easy limit requests to your application.
* RateLimitBundle – Add rate limits to your controllers/actions easily through annotations.
* BazingaHateoasBundle – Integration of the Hateoas library.
* KnpJsonSchemaBundle – Provide a service which allow you to generate json schema based on validation metadata.
* LexikJWTAuthenticationBundle – This bundle provides JWT (Json Web Token) authentication for your REST API using the namshi/jose library.
* ResourceBundle – Bundle that helps in developing REST APIs.
* SerializedResponseBundle – A simple bundle to provide an easy way to send out json/xml/yaml responses of serialized objects with annotations.

Template Engine

* UcoTwigExtensionsBundle – Provides some filters.
* TwigExtraBundle – Twig Extra Tools Extensions.
* twig-inflection – Apply inflection.
* KnpTimeBundle – Provides helpers for time manipulation.
* GravatarBundle – Simple wrapper to gravatar API.
* CgKintBundle – This bundle lets you use the Kint library in your Twig templates.
* TwigJackBundle – Handy additional features for Twig.


* DoctrineFixturesBundle – Integrates the Doctrine2 Data Fixtures library.
* DoctrineMigrationsBundle – Integrates the Doctrine2 Migrations library.
* RelationBundle – Bundle to manage relations between models/entities.
* PasswordStrengthBundle – Validator for ensuring strong passwords.
* StofDoctrineExtensionsBundle – This bundle provides integration for DoctrineExtensions.
* DoctrineEncryptBundle – Bundle allows you to create doctrine entities with fields that will be protected by encryption algorithms such as AES.
* WizadDoctrineDocBundle – Allows you to generate a decent documentation for your doctrine model schema.
* doctrine-routing-bundle – Dynamic database routing.
* FeedBundle – A bundle to build RSS feeds from your entities.
* FPNTagBundle – This bundle adds tagging, with the ability to associate tags with any number of different entities.
* DoctrineEnumBundle – Provides support of MySQL ENUM type for Doctrine2.
* MysqlDoctrineFunctions – MySQL Function for Doctrine : RAND(), ROUND() DATE(), DATE_FORMAT().
* VichGeographicalBundle – A bundle which provides geographical features for ORM and ODM entities and object oriented javascript maps rendering.


* dms-filter-bundle – Provides a FilterService to allow users to implement input filtering in entities using Annotations.


* CaptchaBundle – Bundle implementing a “captcha” form type.
* FilterFormBundle – Filter form bundle.
* CraueFormFlowBundle – Multi-step forms.
* InfiniteFormBundle – A collection of useful form types and extensions.
* IvoryOrderedFormBundle – Provides a form ordering support.
* FormBundle – Provides the “entity_id” type.

Service Container

* JMSDiExtraBundle – Provides Advanced Dependency Injection Features.
* PHP-DI – The dependency injection container for humans.


* TwigReflectionBundle – Displays what’s in Twig.
* WebProfilerExtraBundle – Adding routing, container, assetic & twig information in the web profiler.
* JMSDebuggingBundle – Provides advanced debugging tools.
* LiipCodeBundle – A set of Symfony2 console commands to help developers deal with the various ways of identifying classes, templates, bundles, services, etc.
* ListenersDebugCommandBundle – A console command to debug listeners.
* PUGXGeneratorBundle – An enhancement of SensioGeneratorBundle.
* XhprofBundle – XHProf bundle.

Assets Management

* FkrCssURLRewriteBundle – A small assetic filter to fix all url paths at css documents to correct urls.
* JmikolaJsAssetsHelperBundle – Exposes the AssetsHelper service from Symfony2’s templating component to JavaScript, allowing relative or absolute asset URI’s to be generated client-side.
* IgorwFileServeBundle – Bundle for serving protected files.
* KachkaevAssetsVersionBundle – Automates the process of updating assets version.
* SpritesBundle – Bundle for the Sprites library.
* ZakharovviHumansTxtBundle – Generate humans.txt file from git repository.
* SalvaJshrinkBundle – This bundle integrate jshrink library as Assetic filter and twig extension.
* AsseticMinifierBundle – An assetic minifier in pure PHP for CSS and JS files.
* assetic-extra-bundle – Asset Directory filter for Assetic.


* RabbitMqBundle – RabbitMQ bundle.
* JMSJobQueueBundle – Allows to schedule console commands as jobs.
* GearmanBundle – A bundle intended to provide an easy way to support developers who need to use job queues.
* LeezyPheanstalkBundle – Bundle for Pheanstalk, PHP client for beanstalkd queue.
* qpush-bundle – The QPush Bundle relies on the Push Queue model of Message Queues to provide asynchronous processing in your application.

Payments Management

* JMSPaymentCoreBundle – This bundle provides the foundation for various payment plugins.
* JMSPaymentPaypalBundle – Payment Bundle providing access to the PayPal API.
* CartBundle – High quality cart for developers.

Why to choose symfony

I never gone too much deep over the symfony. However, I experienced it for one of my project. Adhering to an MVC pattern and strict object oriented language Symfony framework allows creating more testable code which can be reused in future and accordingly saves the time.

Choosing Symfony means having a long-term vision of application assets. It also means knowing how to make the day-to-day life of developers much easier.

The advantages of using symfony framework and the answers for the question why to choose symfony are:

1. Empowers Developers :

By taking features that would have previously have taken 100’s of lines of code and compressing them into one simple function call empowers developers to integrate more complex features into their Web Sites.
2. Allow for Quicker development of applications :

This is very relevant for people that need websites created in a very small window .

3. Lower Costs :

Allows programmers to pass cost savings onto the customer, a whole new range of customers generated that wanted a website but previously could not afford the higher development costs.

4.  Symfony tries to bring innovation to PHP:

It was one of the first major frameworks to embrace PHP 5.3, to introduce the usage of a Dependency Injection container, and to use a templating engine for its templates by default, Twig, which is now also adopted by major CMSes like Drupal and eZpublish. Symfony also has some unique features like its gorgeous debug toolbar and its great built-in profiler.