Building A Web App Using Symfony 2: Answer To Your Needs Within...

Building A Web App Using Symfony 2: Answer To Your Needs Within A Single Click

0 6790
Building A Web App Using Symfony 2

Symfony 2 tutorial. Mobile application has taken a huge leap. Today, mobile applications are not just apps anymore – they are actually solutions to business issues. From a simple informative app to a critical business application, mobile apps have become a powerful tool that efficiently supports marketing strategies of a business.

Just open your phone and everything is available in your hands in the form of web apps starting from very basic daily essentials to luxuries and entertainment like music, gaming, banking, shopping, ticketing, billing recharges and so on.

Now the real question is how to build a web app. Thanks to the availability of a wide range of developers who share their experiences and knowledge online, you can easily find the relevant information and documentation on building an app. Similarly like you search ‘how to create a blog‘ and get thousands of solutions, you can search “building a web app using symphony” to get the most relevant answer.

However, before you get started, make sure your web app is:

  • User friendly
  • technically concrete
  • easily accessible
  • Less time consuming
  • Less viable to unauthorized access
  • On the toplist of various search engines like Google, yahoo, playstore etc.

Building a web app is quite a technical process but having a little knowledge of basic languages and learning a basic web development program, you can easily create a web application for your personal use.

In the following series, I will discuss some techniques and key steps that may help you build your own website using Symfony. It is a three-layered process which involves:

Bootstrapping or Rebooting: The very first step is to download the Symfony standard from its official site followed by unzipping the archives to the web root directory.

After this you need to download the PHP packaging system which is known as composer.
Now there can be two possibilities:

1. If you already have the cURL utility installed, issue the following command:
curl -S https://getcomposer.org/installer | php

2. Else issue the below command:
php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

You will get a new downloaded file known as composer.phar. This file is the entry point for our PHP package management.
The files that we have known contain no bundles so as to make Symfony work. For that you need to run:
phpcomposer.phar update

This will install all the required bundles and in case you run into errors i.e. missing utilities or critical dependencies, composer will let you know about that. Depending upon the speed of your connection the aforesaid installation procedure will complete itself within the couple of minutes.

With Symfony, the common practice is to use app_dev.php as the initial page during development, on the other hand when it comes to production app_dev.php would be omitted.

With the resources provided by Symfony one can feel free to search and familiarize themselves with the framework, toolbars and the debug messages without any obstruction.

To get the latest composer.phar framework, you must periodically run composer.phar self-update

There is one more feature provided on Symfony webpage i.e. it has a demo app in the form of a bundle known as AcmeDemoBundle which can be used as an example to build your own app.

Modules (Entities)

In Symfony, modules are also referred to as Bundle, Controllers, Views, and Models. A controller is a collection of files which serves as the canister for logic control, data retrieving and presentation of a particular set of function in your website.

Bundle or controller or entity serves as the foundation of an MVC-structured website.To initiate the application development and generate a bundle, run the following command:

php app/console generate:bundle

The console will ask you various questions before creating a bundle such as:

  • Bundle namespace: Be sure to have "Bundle" at the end.
  • Bundle name: use the suggested name derived from the namespace.
  • Target Directory
  • Configuration format: You are available with 4 options i.e. PHP, YAML, XML and annotation. You can opt for any one.
  • Would you like to generate the whole directory structure: Not necessary.
  • Confirm the kernel update, generation and Routing generation.

Routing

Routing is nothing but a mapping mechanism which processes the request, grabs the data and render the response to the web browser. You can download all the routes via app/config/routing.yml
You have the provision for defining your own route. You can create your route in MyBundle/Resouces/config and then import the same in app/config/routing.yml:

Acme_hello:
	Resource: "@AcmeHelloBundle/Resouces/config/routing.yml"

Database

Configuring the database with Symfony 2 is relatively simpler and can be done by issuing the following command app/config/parameters.yml:

parameters:
database_driver: pdo_mysql
database_host: 127.0.0.1
database_port: null
database_name: symfony
database_user: root
database_password: null

Parameters that can be customized in a database are:
- database name
- user
- password

Once the database is created, same can be imported into Symfony:

php app\console doctrine:mapping:import

Followed by the creation of corresponding entities by:

php app\console doctrines:generate:entitytr

(Or wherever is the namespace of the bundle).
Symfony usually supports two ORMs: Doctrine and Propel. You can go for any one of the ORM.

DEVELOPMENT:

We are ready with the framework set up and database. Next step is to make it functional by creation of routes, controllers, repositories and templates.

Routes

Format used by Symfony in order to configure the routes for various applications is YAML Format. One of the examples illustrating the same is mentioned below:
File location: src/tr/rsywxBundle/Resources/config/routing.yml

home:
pattern:  /
defaults: { _controller: trrsywxBundle:Default:index }

contact:
pattern: /contact
defaults:
        _controller: FrameworkBundle:Template:template
template: 'trrsywxBundle:Default:contact.html.twig'

book_list:
pattern: /books/list/{page}/{key}
defaults: 
page: 1
key: null
        _controller: trrsywxBundle:Book:list

books_search: 
pattern: /books/search
defaults: {_controller: trrsywxBundle:Book:search}
requirements: 
        _method: POST        

book_detail:
pattern: /books/{id}.html
defaults: { _controller: trrsywxBundle:Book:detail}

Very first requirement of an app is its entry point which is the "home" route. Pattern defines the URI pattern which the route should match.
At an entry point, / is used. defaults:_controller states the action of the application when the route is matched.

Controllers

After routes come Controllers. There are a total of 4 controllers named BookController.php, DefaultController.php, LakersController.php, and ReadingController.php located in src/tr/rsywxBundle/Controller.
Two controllers are illustrated below matching book_list and books_search.

<?php

classBookController extends Controller {
  // ... Many other functions here, see source

  public function listAction($page, $key) {
    $em = $this->getDoctrine()->getManager(); // Get the Entity Manager
    $rpp = $this->container->getParameter('books_per_page'); // Get the global parameter for how many books to show on one page

    $repo = $em->getRepository('trrsywxBundle:BookBook'); // Get the repository

    list($res, $totalcount) = $repo->getResultAndCount($page, $rpp, $key); // Get the result

    $paginator = new \tr\rsywxBundle\Utility\Paginator($page, $totalcount, $rpp); // Init the paginator
    $pagelist = $paginator->getPagesList(); // Get the pagelist used for navigation 

    return $this->render('trrsywxBundle:Books:List.html.twig', array('res' => $res, 'paginator' => $pagelist, 'cur' => $page, 'total' => $paginator->getTotalPages(), 'key'=>$key)); // Render the template using necessary parameters
  }

  public function searchAction(Request $req) {
    $q = $req->request->all(); // Get the posted data

    $page = 1; // Get which page to display 
    $key = $q['key']; // Get the search criteria

    $em = $this->getDoctrine()->getManager();
    $rpp = $this->container->getParameter('books_per_page');

    $repo = $em->getRepository('trrsywxBundle:BookBook');

    list($res, $totalcount) = $repo->getResultAndCount($page, $rpp, $key);

    $paginator = new \tr\rsywxBundle\Utility\Paginator($page, $totalcount, $rpp);
    $pagelist = $paginator->getPagesList();

    return $this->render('trrsywxBundle:Books:List.html.twig', array('res' => $res, 'paginator' => $pagelist, 'cur' => $page, 'total' => $paginator->getTotalPages(), 'key' => $key));
  }
}

Typically a controller will input parameters, get the entity manager and display the results after necessary processing.

Entities and Repositories

Entities are the reflection of database in which we should use straightforward commands to CRUD the data. Repositories are nothing but a customized way to manipulate data.

Entities are generated via a console/terminal command: php app\console doctrine:generate:entity. The location of generated files is src/tr/rsywxBundle/Entity.

Change the ORM mapping files located at

src/tr/rsywxBundle/Resources/config/doctrine)
and build mandatory functions like retrieving data to build a repository.
For example:

File location: src/tr/rsywxBundle/Resources/config/doctrine/BookBook.orm
tr\rsywxBundle\Entity\BookBook:
type: entity
repositoryClass: tr\rsywxBundle\Entity\BookRepository # Add this line to state that you will use BookRepository.php as the repository class for BookBook table
table: book_book
fields:
    ...

After that, run php app\console doctrine:generate:entity again. Now notice that a new BookRepository.php file is created under src/tr/rsywxBundle/Entity. Afterwards open that file and you will be able to create your own functions for data manipulation:

public function getResultAndCount($page, $rpp, $key=null) {
  // Get the book count
  $em = $this->getEntityManager();
  if ($key == 'null') {
    $q1 = $em->createQuery('select count(b.id) bc from trrsywxBundle:BookBook b');
  } else {
    $qstr = sprintf("select count(b.id) bc from trrsywxBundle:BookBook b where b.title like '%s%%'", $key);
    $q1 = $em->createQuery($qstr);
  }
  $res1 = $q1->getSingleResult();
  $count = $res1['bc'];

  // Now get the wanted result specified by page
  $repo = $em->getRepository('trrsywxBundle:BookBook');
  $q2 = $repo->createQueryBuilder('r')
    ->setMaxResults($rpp)
    ->setFirstResult(($page - 1) * $rpp)
    ->orderBy('r.id', 'desc');
  if ($key <> 'null') {
    $key = $key . '%';
    $q2->where('r.title like :key')
      ->setParameter('key', $key);
  }

  $q2 = $q2->getQuery();
  $res2 = $q2->getResult();
  return array($res2, $count);
}

Views and Templates

Nothing can be represented without a view as a view is equivalent to a template according to the Symfony.

A template defines how your app would appear to the users. It is a text file that generates a text-based format. PHP template is one of the most popular templates that has a combination of PHP and text code.

As an instance:

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome to Symfony!</title>
  </head>
  <body>
    <h1><?php echo $page_title ?></h1>

    <ul id="navigation">
      <?php foreach ($navigation as $item): ?>
        <li>
          <a href="<?php echo $item->getHref() ?>">
            <?php echo $item->getCaption() ?>
          </a>
        </li>
      <?php endforeach ?>
    </ul>
  </body>
</html>

Finalizing:

After bootstrapping and development the project is finalized with some advanced techniques like pagination, image watermarks etc.

Image watermarks

Image watermarks refer to the display of image after processing which can be done as follows:

cover: 
pattern: /books/cover/{id}_{title}_{author}_{width}.png
defaults: {_controller: trrsywxBundle:Default:cover, width: 300}

In a template, invoke the call to show the routed image by:

<imgsrc="{{path("cover", {'id':book.id, 'author':author, 'title':book.title}) }}" alt="{{book.title}}'s cover" title="{{book.title}}'s cover"/>

A processed image will be shown every time an image tag i.e. <img> comes across.
This is not the complete set of tutorial from Symfony but a brief introduction that might help you make a wiser decision by choosing Symfony for building a web application for your use.

Author Bio: Rachael Wright, an outreaching expert to increase the brand visibility with effective content marketing campaigns. She works with 6S Digital Marketing Solutions, a content marketing company, to help SMEs and large business sectors from planning to execution of effective content campaigns.

SIMILAR ARTICLES


NO COMMENTS

Leave a Reply