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

PHP Beginner Tutorial #Day1

What is PHP?

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP.

  • Serverside scripting language
  • Used for web development
  • Generate dynamic web pages

Requirements

What you will need?

  • Computer with PHP installed
  • Text editing application
  • A web browser

What would be helpful?

  • Understanding of HTML
  • Understanding of programming concept
  • Understanding how web server works

Terminologies 

Hypertext

Hypertext is text that links to other information. By clicking on a link in a hypertext document, a user can quickly jump to different content.

Preprocessor

In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers.

Serverside Scripting Language

Those scripts were executed by the operating system, and the results were served back by the web server. Many modern web servers can directly execute on-line scripting languages such as ASP, JSP, Perl, PHP and Ruby either by the web server itself or via extension modules (e.g. mod_perl or mod_php) to the web server.

HTML

HyperText Markup Language (HTML) is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS), and JavaScript, it forms a triad of cornerstone technologies for the World Wide Web.

HTTP

A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Webpages to users, in response to their requests, which are forwarded by their computers’ HTTP clients.

Web Development

Web development broadly refers to the tasks associated with developing websites for hosting via intranet or Internet. The Web development process includes Webdesign, Web content development, client-side/server-side scripting and network security configuration, among other tasks.

Dynamic Webpage

A dynamic web page is a web page that displays different content each time it’s viewed. For example, the page may change with the time of day, the user that accesses the webpage, or the type of user interaction.

 

web server working
web server working

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.

Data Warehouse Manager

The Data Warehouse (DW) Manager provides leadership of all aspects of DW activities including oversight of the design and development of the new Warehouse, management of Current/Future reporting requirements, and oversight of the Extract, Transform and Load (ETL) processes.

The perceived strength of data warehousing within an organization will be the sum of the strength of the Project Managers. Project Managers must deliver commitments and must deliver on time. They will do this by culling resources from within the data warehouse team and from consultancy as necessary and establishing partnerships with other internal support organizations required to support a data warehouse iteration. A Project Manager delivers by:

• Maintaining a highly detailed plan and obsessively caring about the progress on it.
• Applying personal skill and judgment to everything on the project. This is a real value-add of the
Project Manager. It is the Project Manager’s job to exercise relevant discretion.
• Matching team member’s skills and aspirations as closely as possible to tasks on the plan.
• Tracking all relevant metrics for each iteration:
– Project Plan milestones
– Issues list
– Adherence to change control practices
– Adherence to source code control practices
– Documentation fit for users and support personnel
– Architectural components adherence to fit for purpose and standards
– Regression testing performed and tests updated based on changes
– Team members fit for tasks and career-enhanced