Category Archives: Frameworks

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:

<?php

// 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()
    {
        $this
          ->setName('sessions:check')
          ->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
            $total_active_auth_count++;

            // 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));

        $output->writeln(sprintf(
            '%s user(s) were active, and %s of them was/were logged in.',
            $total_active_count,
            $total_active_auth_count
        ));
    }
}

Laravel Installation – The Fastest Way

Run the following command using composer:

composer global require "laravel/installer=~1.1"

Put an alias to the freshly installed Laravel installer in your user configuration .bashrc:

nano ~/.bashrc

And place this inside the file:

alias laravel='~/.composer/vendor/bin/laravel'

And run the following to make sure your bashrc profile is reloaded:

source ~/.bashrc

Once installed, the simple laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog would create a directory named blog containing a fresh Laravel installation with all dependencies installed. This method of installation is much faster than installing via Composer:

laravel new blog

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;
}

Usage:

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

doctrine_cache:
    aliases:
        cache_categories: classifiad_category_cache
    providers:
        classifiad_category_cache:
            mongodb:
                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.

Database

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

Validation

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

Forms

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

Development

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

Queues

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

Best High Ranking PHP Frameworks for Web Developers

Today I’m going to share the most high ranking PHP frameworks for web developers to achieve the high performance. Based on research in many web sites and my experience I’m sharing this information.

1. Symfony

Symfony created in 2005 a very powerful MVC Framework, Drupal the most popular Open-Source CMS uses Symfony components.

Faster and less greedy
Unlimited flexiblity
Ease of use
Stable and sustainable
A driver of innovation
Interoperable

More Info

2. Zend

Zend Framework is based on simplicity, object-oriented best practices, leading provider of software and services for developing, deploying and managing business-critical applications in PHP.

Agile Design
Continuous Delivery
Cloud Scale

More Info

3. Laravel

Larvael is very fast growing PHP Framework and very easy to learn and use.

RESTful Routing
Command Your Data
Beautiful Templating
Proven Foundation

More Info

4. Cake PHP

CakePHP is a rapid development framework for PHP which uses commonly known design patterns like ActiveRecord, Association Data Mapping, Front Controller and MVC.

Build Quickly
No Configuration
Friendly License
Batteries Included
Clean MVC Conventions
Secure

More Info

5. YII

Yii is the most popular PHP framework and its last updated 1.1.14 version on 11th August 2013.

Fast

loads the features that you need
Powerful caching support
Explicitly designed to work efficiently with AJAX

Secure

Input validation
Output filtering
SQL injection and Cross-site scripting prevention

Professional

Helps you develop clean and reusable code
Follows the MVC pattern
Ensuring a clear separation of logic and presentation

More Info

6. CodeIgniter

CodeIgniter comes 2nd in our ranking and its very powerful framework in PHP simple and elegant toolkit to create full-featured web applications.

Exceptional performance.
Nearly zero configuration.
Clear, thorough documentation.
Framework with a small footprint.
Simple solutions to complexity.

More Info

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.