Category Archives: PHP

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

5 things you must know about PHP 7

1. THE LATEST PHP VERSION WILL BE RELEASED LATER THIS YEAR

The PHP 7 Timeline RFC was approved in a near unanimous vote, and aims to release PHP 7 in October 2015. Even if it’s delayed a bit, we’re still likely to see it before the year is out!! The final feature set for PHP 7 is almost completely finalized, and will officially close by the end of March.

2. PHP SPACE SHIPS

PHP 7 will introduce a new operator <=> conveniently similar to a TIE fighter and dubbed the Spaceship Operator. It can be used for combined comparisons – mostly when dealing with sorting.

3. DECLARATIONS & SCALER TYPE HINTS

PHP 7 will allow developers to declare what kind of return type a function is expected to have – similar to argument Type Hints.

In addition, argument type hints and the new return-type declarations now support new scalar types, allowing developers to denote that they’re expecting strings, floats, ints or bools to be passed or returned.

4. PHP 7 PERFORMANCE

PHP 7 is based on the PHPNG project (PHP Next-Gen), that was led by Zend to speed up PHP applications. The performance gains realized from PHP 7 are huge! They vary between 25% and 70% on real-world apps, and all of that just from upgrading PHP, without having to change a single line of code!

5. PHP 7 IS 2X FASTER

Since PHPNG was open sourced and later merged into PHP 7, its performance more than doubled in many cases, and we’re continuing to improve it all the time.

To put things in perspective – when PHPNG was published, the WordPress homepage required approx. 9.4 billion CPU instructions to execute. As of now – it requires only 2.6 billion – that’s 72% less!

Explore more here.

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

Singleton Design Pattern in PHP

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

The following code is a simple implementation:



class Database
{
    // A static property to hold the single instance of the class
    private static $instance;

    // The constructor is private so that outside code cannot instantiate
    private function __construct() { }

    // All code that needs to get and instance of the class should call
    // this function like so: $db = Database::getInstance();
    public function getInstance()
    {
        // If there is no instance, create one
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    // Block the clone method
    private function __clone() {}
}

// To use, call the static method to get the only instance
$db = Database::getInstance();


Pros and Cons of Singeleton Design Pattern :

pro : You know you have the same instance available at all times.
con : One and only one instance is all you get.
pro : Instantiate itself for you so all you need to do is get it.
con : Autoinstantiation diminishes flexibility of argument passing.
pro : Since it is singeleton it can replace global variable declaration.
con : Since it is singeleton it can replace global variable declaration.

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

Backup Your MySQL Database Using PHP

Here is the script to backup MySql database using php. Cheers!



‹?php  
// Check via PhpMyAdmin to see what character database is using
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$tables = '*';
//get all of the tables
if($tables == '*')
{
    $tables = array();
    $result = mysql_query('SHOW TABLES');
    while($row = mysql_fetch_row($result)) {
    $tables[] = $row[0];
}
}
else
{
    $tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);
    $return.= 'DROP TABLE '.$table.';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return.= "\n\n".$row2[1].";\n\n";
    for ($i = 0; $i < $num_fields; $i++)
    {
        while($row = mysql_fetch_row($result))
        {
            $return.= 'INSERT INTO '.$table.' VALUES('; for($j=0; $j<$num_fields; $j++) { $row[$j] =             addslashes($row[$j]);
            $row[$j] = ereg_replace("\n","\\n",$row[$j]);
            if (isset($row[$j]))
            {
                $return.= '"'.$row[$j].'"' ;
            }
            else
            {
                $return.= '""';
            }
            if ($j<($num_fields-1))
            {
                $return.= ',';
            }
        }  
        $return.= ");\n";
    }
}
$return.="\n\n\n";
}
//save file
$handle = fopen('backups/db-backup-'.date('Y-m-d H:i:s').'-'.(md5(implode(',',$tables))).'.sql','w+'); fwrite($handle,$return); fclose($handle); if($handle)
{
    echo "database is successfully stored in backups directory.";
}
else
{
    echo "database backup unsuccessfuly.";
}