PHP Professional এবং Zend Certified PHP Engineer (ZCPE ) Course এ সীমিত সংখ্যক আসন বাকি আছে। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

CRUD with Symfony2

In this tutorial I will show a simple CRUD application with Symfony2. I will use mostly command prompt. So, to prepare your system for this tutorial please read previous tutorial. Otherwise, it will confusing for you.

Symfony

Before start we need to clear some ideas, like MVC. Hope you already have enough understanding with MVC pattern.

Model (M) : it connect with database and handle data and contain business logic.
View (V) : contains the html, colours and images.
Controller (C) : mainly interact with database and view.

CRUD

For the model Symfony2 use(default) ORM for its tasks called entity. Now question is what is ORM?

ORM?

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. And we will use Doctrine for our ORM.

Doctrine

At the beginning it would be intimidating. But, by the time being you will see the usefulness of it.

And in the view we will use twig.

Twig!!!

Twig is a template engine for PHP. It is fast, secure and flexible. And you will also see the simplicity of twig when you are going to use it.

twig

So lets plan for our CRUD project. We will create a single table database for our Book inventory. It will contains following informations –

name
author
language
publisher
summary

Now, start with a fresh installation of Symfony2.

Something about Bundle
We need to create our project bundle. Bundle contains all the necessary project source code.
A bundle is also a PHP namespace. The namespace must follow the technical interoperability standards for PHP 5.3 namespaces and class names: it starts with a vendor segment, followed by zero or more category segments, and it ends with the namespace short name, which must end with a Bundle suffix.

A namespace becomes a bundle as soon as you add a bundle class to it. The bundle class name must follow these simple rules:

– Use only alphanumeric characters and underscores;
– Use a CamelCased name;
– Use a descriptive and short name (no more than 2 words);
– Prefix the name with the concatenation of the vendor (and optionally the category namespaces);
– Suffix the name with Bundle.

Here are some valid bundle namespaces and class names:

Namespace Bundle Class Name
Acme\Bundle\BlogBundle AcmeBlogBundle
Acme\Bundle\Social\BlogBundle AcmeSocialBlogBundle
Acme\BlogBundle AcmeBlogBundle

So, let’s create our book inventory with namespaces and bundle.

Step 1:
Open your command prompt and go to your project folder called “symfony”. (we have created it previous tutorial)

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

You will found something like –


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 CustomBookBundle.

Bundle name [CustomBookBundle]: CustomBookBundle

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

Target directory [/xampp/htdocs/sfy/symfony/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\BookBundle\CustomBookBundle" bundle
in "/xampp/htdocs/sfy/symfony/src/" using the "annotation" 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 open your browser and go to –

http://localhost/sfy/symfony/web/app_dev.php/hello/book

Let’s discuss about what we have done so far.

  • We have created our project bundle with command prompt
  • By default it creates one controller called “DefaultController” inside /src/Custom/BookBundle/Controller/ folder and default indexAction takes one argument. Let’s change it to –
    
    namespace Custom\BookBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    
    class DefaultController extends Controller
    {
        public function indexAction()
        {
            return $this->render('CustomBookBundle:Default:index.html.twig');
        }
    }
    
    
  • The DefaultControler and indexAction is called from routing and it written in yml. It’s located in “/src/Custom/BookBundle/Resources/config/routing.yml“. lets change this one as well to –

    custom_book_homepage:
    path: /hello
    defaults: { _controller: CustomBookBundle:Default:index }

  • The view exists inside “/src/Custom/BookBundle/Resources/views/Default/index.html.twig“. Let’s change this one as well –
    <h1>Hello !!!</h1>
    

Now browse to –

http://localhost/sfy/symfony/web/app_dev.php/hello

Now hello is not taking any argument.

Step 2:

$ php app/console doctrine:generate:entity

Welcome to the Doctrine2 entity generator

This command helps you generate Doctrine2 entities.

First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name: CustomBookBundle:Book
C←[K←7ustomBookBundle←8u←[K←7stomBookBundle←8s←[K←7tomBookBundle←8t←[K←7omBookBu
ndle←8o←[K←7mBookBundle←8m←[K←7BookBundle←8B←[K←7ookBundle←8o←[K←7okBundle←8o←[K
←7kBundle←8k←[K←7Bundle←8B←[K←7undle←8u←[K←7ndle←8n←[K←7dle←8d←[K←7le←8l←[K←7e←8
e←[K:←[KB←[Ko←[Ko←[Kk←[K

Determine the format to use for the mapping information.

Configuration format (yml, xml, php, or annotation) [annotation]: annotation
a←[K←7nnotation←8n←[K←7notation←8n←[K←7otation←8o←[K←7tation←8t←[K←7ation←8a←[K←
7tion←8t←[K←7ion←8i←[K←7on←8o←[K←7n←8n←[K

Instead of starting with a blank entity, you can add some fields now.
Note that the primary key will be added automatically (named id).

Available types: array, simple_array, json_array, object,
boolean, integer, smallint, bigint, string, text, datetime, datetimetz,
date, time, decimal, float, blob, guid.

New field name (press to stop adding fields): name
Field type [string]:

Field length [255]:

New field name (press to stop adding fields): author
Field type [string]:

Field length [255]: 200

New field name (press to stop adding fields): language
Field type [string]:

Field length [255]: 100

New field name (press to stop adding fields): publisher
Field type [string]:

Field length [255]: 100

New field name (press to stop adding fields): summary
Field type [string]: text
t←[K←7ext←8e←[K←7xt←8x←[K←7t←8t←[K

New field name (press to stop adding fields):

Do you want to generate an empty repository class [no]?

Summary before generation

You are going to generate a "CustomBookBundle:Book" Doctrine2 entity
using the "annotation" format.

Do you confirm generation [yes]?

Entity generation

Generating the entity code: OK

You can now start using the generated code!

First of create a database with phpmyadmin call “sym” and run the following command –

$ php app/console doctrine:schema:update --force


Updating database schema...
Database schema updated successfully! "1" queries were executed

$ php app/console generate:doctrine:crud

Welcome to the Doctrine2 CRUD generator

This command helps you generate CRUD controllers and templates.

First, you need to give the entity for which you want to generate a CRUD.
You can give an entity that does not exist yet and the wizard will help
you defining it.

You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name: CustomBookBundle:Book

By default, the generator creates two actions: list and show.
You can also ask it to generate "write" actions: new, update, and delete.

Do you want to generate the "write" actions [no]? yes

Determine the format to use for the generated CRUD.

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

Determine the routes prefix (all the routes will be "mounted" under this
prefix: /prefix/, /prefix/new, ...).

Routes prefix [/book]:

Summary before generation

You are going to generate a CRUD controller for "CustomBookBundle:Book"
using the "yml" format.

Do you confirm generation [yes]?

CRUD generation

Generating the CRUD code: OK
Generating the Form code: OK
Confirm automatic update of the Routing [yes]?
Importing the CRUD routes: OK

You can now start using the generated code!

Now open your browser and go to –

http://localhost/sfy/symfony/web/app_dev.php/book/

Your crud is done. Populate data to your Symfony2 web app.

Symfony CRUD

If you open your project folder with your IDE, you will see one BookController is created inside “/src/Custom/BookBundle/Controller/

Open “/src/Custom/BookBundle/Entity/” folder. Book.php contains all Doctrine for our ORM support.

And in “/src/Custom/BookBundle/Resources/views/Book/” folder all the twig files exists for our view.

By the way, you can download all the code from my –

In this tutorial we have used command prompt to generate code. From next tutorial, we will analyze each part of the code gradually.

Happy coding… 🙂

CRUD with 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.

9 comments on “CRUD with Symfony2

Leave a Reply

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