আগামী ৩০ নভেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML, CSS PHP,MySQL,JavaScript, AJAX, JQUERY, Bootstrap and Live Project কোর্সের ৮৭ তম ব্যাচ এবং ৫ ডিসেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে চার মাস ব্যাপী Zend PHP-7 Certified PHP Engineering (Advance PHP) কোর্সের ৩৫ তম ব্যাচ। প্রত্যেকটি কোর্স এর ফী নির্ধারণ করা হয়েছে ৩০,০০০/= আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722 81 75 91

FOSUserBundle of Symfony2

What is Bundle?
Bundles are pieces of software, which is created for first feature development. Symfony has lots of bundles in the web. You can find all amazing bundles information in http://knpbundles.com/ which are categorized by popularity, rating, recommendation etc.

What is FOSUserBundle?
The FOSUserBundle adds support for a database-backed user system in Symfony2. It provides a flexible framework for user management that aims to handle common tasks such as user registration and password retrieval.

Features include:
– Users can be stored via Doctrine ORM, MongoDB/CouchDB ODM or Propel
– Registration support, with an optional confirmation per email
– Password reset support
– Unit tested

Lets start a fresh project with Symfony2 –

$ composer create-project symfony/framework-standard-edition fosuser/

Installing symfony/framework-standard-edition (v2.6.6)
- Installing symfony/framework-standard-edition (v2.6.6)
Loading from cache

Created project in fosuser/
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
- Installing doctrine/lexer (v1.0.1)
Loading from cache
.
.
.
.
.
Generating autoload files
Would you like to install Acme demo bundle? [y/N] N
Creating the "app/config/parameters.yml" file
Some parameters are missing. Please provide them.
database_driver (pdo_mysql):
database_host (127.0.0.1):
database_port (null):
database_name (symfony): fosuser
database_user (root):
database_password (null):
mailer_transport (smtp):
mailer_host (127.0.0.1):
mailer_user (null):
mailer_password (null):
locale (en):
secret (ThisTokenIsNotSoSecretChangeIt): fosuser
Clearing the cache for the dev environment with debug true
Trying to install assets as symbolic links.
Installing assets for Symfony\Bundle\FrameworkBundle into web/bundles/framework
The assets were installed using symbolic links.
Installing assets for Sensio\Bundle\DistributionBundle into web/bundles/sensiodistribution
The assets were installed using symbolic links.
$

Now go to with your browser –

http://localhost/fosuser/web/app_dev.php/

If you see something like this then you are good to go—

Symfony2 installation success

Scary, right!!!

We need to create a bundle for our project, first. Let’s do it—


$ php app/console generate:bundle --namespace=Custom/UserBundle

Welcome to the Symfony2 bundle generator

In your code, a bundle is often referenced by its name. It can be the
concatenation of all namespace parts but it's really up to you to come
up with a unique name (a good practice is to start with the vendor name).
Based on the namespace, we suggest CustomUserBundle.

Bundle name [CustomUserBundle]:

The bundle can be generated anywhere. The suggested default directory uses
the standard conventions.

Target directory [/Applications/XAMPP/xamppfiles/htdocs/fosuser/src]:

Determine the format to use for the generated configuration.

Configuration format (yml, xml, php, or annotation): yml

To help you get started faster, the command can generate some
code snippets for you.

Do you want to generate the whole directory structure [no]? yes

Summary before generation

You are going to generate a "Custom\UserBundle\CustomUserBundle" bundle
in "/Applications/XAMPP/xamppfiles/htdocs/fosuser/src/" using the "yml" format.

Do you confirm generation [yes]?

Bundle generation

Generating the bundle code: OK
Checking that the bundle is autoloaded: OK
Confirm automatic update of your Kernel [yes]?
Enabling the bundle inside the Kernel: OK
Confirm automatic update of the Routing [yes]?
Importing the bundle routing resource: OK

You can now start using the generated code!

$

Now change the following line of code from app/config/config.yml


framework: translator: ~

Let’s download our FOSUserBundle using composer. In our composer.json add –


"require": {
"friendsofsymfony/user-bundle": "~1.3"
}

Tell the composer to download it –


$ php composer update friendsofsymfony/user-bundle

Now tell the Kernel, we have new bundle in app/AppKernel.php.

$bundles = array(        
 // ...         
new FOS\UserBundle\FOSUserBundle(),     
);

Create a User.php file in src/Custom/UserBundle/Entity/

namespace Custom\UserBundle\Entity;

use FOS\UserBundle\Entity\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();
    }
}

Update app/config/security.yml as follows –


security:
providers:
fos_userbundle:
id: fos_user.user_provider.username

encoders:
FOS\UserBundle\Model\UserInterface: sha512

firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
logout: true
anonymous: true

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 }

role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN

Add the following lines of code in app/config/config.yml


fos_user:
db_driver: orm
firewall_name: main
user_class: Custom\UserBundle\Entity\User

Now, add the following routing info in app/config/routing.yml


fos_user_security:
resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile

fos_user_register:
resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
prefix: /register

fos_user_resetting:
resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /resetting

fos_user_change_password:
resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
prefix: /profile

Now update your schema –


$ php app/console doctrine:schema:update --force
Updating database schema...
Database schema updated successfully! "1" queries were executed
$

Let’s check what we have created so far for in our db –

fosuser db

We haven’t created any field but all the fields created by FOSUserBundle!!!

Now check what functionalities we are going to get for free –


$ php app/console router:debug
[router] Current routes
Name Method Scheme Host Path
_wdt ANY ANY ANY /_wdt/{token}
_profiler_home ANY ANY ANY /_profiler/
_profiler_search ANY ANY ANY /_profiler/search
_profiler_search_bar ANY ANY ANY /_profiler/search_bar
_profiler_purge ANY ANY ANY /_profiler/purge
_profiler_info ANY ANY ANY /_profiler/info/{about}
_profiler_phpinfo ANY ANY ANY /_profiler/phpinfo
_profiler_search_results ANY ANY ANY /_profiler/{token}/search/results
_profiler ANY ANY ANY /_profiler/{token}
_profiler_router ANY ANY ANY /_profiler/{token}/router
_profiler_exception ANY ANY ANY /_profiler/{token}/exception
_profiler_exception_css ANY ANY ANY /_profiler/{token}/exception.css
_configurator_home ANY ANY ANY /_configurator/
_configurator_step ANY ANY ANY /_configurator/step/{index}
_configurator_final ANY ANY ANY /_configurator/final
_twig_error_test ANY ANY ANY /_error/{code}.{_format}
user ANY ANY ANY /user/
user_show ANY ANY ANY /user/{id}/show
user_new ANY ANY ANY /user/new
user_create POST ANY ANY /user/create
user_edit ANY ANY ANY /user/{id}/edit
user_update POST|PUT ANY ANY /user/{id}/update
user_delete POST|DELETE ANY ANY /user/{id}/delete
custom_user_homepage ANY ANY ANY /hello/{name}
homepage ANY ANY ANY /app/example
$

Now go to http://localhost/fosuser/web/app_dev.php/login

What you see? The login form is ready to go. But we don’t have any user in our database.

Let’s create one user to check our form is working –


$ php app/console fos:user:create
Please choose a username:shahjalal
Please choose an email:shahjalal.tipu@gmail.com
Please choose a password:shahjalal
Created user shahjalal
$

Try to login and go to your login page again. Now you will see the logout link.

The forms are looking ugly right!!!

fos user profile

Let’s make it beautiful. In src/Custom/UserBundle we have CustomUserBundle.php update is as follows. Because we want to overwrite the default templates we got with FOSUserBundle.

<?php

namespace Custom\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CustomUserBundle extends Bundle
{
	public function getParent()
    {
        return 'FOSUserBundle';
    }
}

Now create a layout.html.twig file inside src/Custom/UserBundle/Resources/views folder –

{% extends '::base.html.twig' %}

{% block body %}
    {{ block('fos_user_content') }}
{% endblock %}

We are extending our base layout which is inside app/Resources/views folder. Now update —

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}Welcome!{% endblock %}</title>
        
        {% block stylesheets %}
        <link rel="stylesheet" type="text/css" href="{{ asset('css/bootstrap-3.3.4-dist/css/bootstrap.min.css') }}">
        
        {% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
    </head>
    <body>
        <div class="container">
            <div class="hero-unit">
                <h1>Symfony2 FOSUserBundle Tutorial</h1>
            </div>
            <div class="row">
                <div class="span12">
                    {% block body %}{% endblock %}
                </div>
            </div>

            <footer>
                <p>&copy; Shahjalal {{ '' | date('Y') }} </p>
            </footer>
        </div>
        
        {% block javascripts %}{% endblock %}
    </body>
</html>

For our purpose lets change our login form. So, copy FOS/UserBundle/Resources/views/Security folder to our src/Custom/UserBundle/Resources/views folder. And add some div in login form.

{% extends "FOSUserBundle::layout.html.twig" %}

{% block fos_user_content %}
{% if error %}
    <div>{{ error|trans({}, 'FOSUserBundle') }}</div>
{% endif %}

<form action="{{ path("fos_user_security_check") }}" method="post">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />

<div>
    <label for="username">{{ 'security.login.username'|trans({}, 'FOSUserBundle') }}</label>
    <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</div>

<div>
    <label for="password">{{ 'security.login.password'|trans({}, 'FOSUserBundle') }}</label>
    <input type="password" id="password" name="_password" required="required" />
</div>

<div>
    <input type="checkbox" id="remember_me" name="_remember_me" value="on" />
    <label for="remember_me">{{ 'security.login.remember_me'|trans({}, 'FOSUserBundle') }}</label>
</div>
<div>
    <input type="submit" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</div>
</form>
{% endblock fos_user_content %}

Now go to your login form again. All are well organized. You can add as much style as possible –

fosuser login page

For simplicity I have only shown one form. But you can change all the styles for all pages. The rules are same…

You can download all the source code from — Source code

Happy coding… 🙂

FOSUserBundle of Symfony2

Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.

Leave a Reply

Your email address will not be published. Required fields are marked *