PHP – Introduction

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


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



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.


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.


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.


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


Common uses of PHP

  • PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
  • PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user.
  • You add, delete, modify elements within your database through PHP.
  • Access cookies variables and set cookies.
  • Using PHP, you can restrict users to access some pages of your website.
  • It can encrypt data.

Characteristics of PHP
Five important characteristics make PHP’s practical nature possible −

  1. Simplicity
  2. Efficiency
  3. Security
  4. Flexibility
  5. Familiarity

“Hello World” Script in PHP

To get a feel for PHP, first start with simple PHP scripts. Since “Hello, World!” is an essential example, first we will create a friendly little “Hello, World!” script.

As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML (or XHTML if you’re cutting-edge) you’ll have PHP statements like this −

      <title>Hello World</title>
      <?php echo "Hello, World!";?>


It will produce following result −

Hello, World!

5 things you must know about PHP 7


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.


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.


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.


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!


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;


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

        cache_categories: classifiad_category_cache
                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

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.


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


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


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


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


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

Web Enthusiastic, Nature Lover