Monthly Archives: July 2017

Facade Pattern – Design Pattern


Intent of facade is to provide the ease of use to any library(subsystem) through a an interface/class.

The Facade Pattern provides a unifide interface to a set of Interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.

Here We can take example of a complex theater system. For playing a movie we may need to set a different programs of each subsystem, Now We can look at facade is some thing like that reduces steps in performing a task, rather than tuning each individual program to work.

In below example TheaterFacade object makes easier to operate programs.

class TheaterFacade {
    public $dvd, $music, $movie, $player;

    public function TheaterFacade(DVD $dvd, Music $music, Movie $movie, Player $player)
        $this->dvd = $dvd;
        $this->music = $music;
        $this->movie = $movie;
        $this->player = $player;

    public function playMovie($movieName)

    public function stopMovie()


class Music {
    public function setMusic($volume)
      //setting volume function

    public function stopMusic()
      //stop function

class Player {
    public function play(){
       //play function

    public function stop(){
       //stop player function


class Movie {

    public function setMovie ($movie) {
        //set movie to play

Adapter pattern – Design Pattern

adapter pattern

Lets Have a Look at adapter pattern definition, that states clearly about its use case.

The Adapter pattern converts the interface of a class into another Interface that client expect. Adapter lets classes work together that could not just because of incompatible interfaces

lets have a look at below code that will give you a better idea.


class ENumeration Implements Iterator {

    protected $enumobj; // will hold the Adaptee class instance

    public function ENumertion(Enum enumObject)
        $this->enumobj = enumObject;

    public function hasNext()
        return $this->enumobj->hasNextElement();

        //NOTE here hasNextElement method is lying in Enum class, call to hasNext() is being tranfered to Enum class objects hasNextElement() method.

    public function next()
        return $this->enumobj->getNextElement();
        //NOTE here getNextElement method is lying in Enum class, call to next() is being tranfered to Enum class object's getNextElement() method.


Now any call using Enumeration class object will be calling Enum class methods, so acting as an adapter to Enum class, caller class doesnot know that it call is being transfered to Enum class.

Hope above example make sense, although if you have any query you can connect with me over comments or by any means.

Collections In Laravel


We can think Collection as Objects of objects. It works as a wrapper over an array by providing some more methods. As every item in Collection have some objects, It will be able to give some extra features like (Paging results, Checking for odd or even, ->isOdd(), etc.)

In general a collection can be referred as a set that can contain any can kind of data object like (Array, ArrayList(In java), LinkedList, Vector, Stack, Queue, etc.)

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We’ll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:

$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
->reject(function ($name) {
return empty($name);

As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array.

In general, collections are immutable(means to say unchangeable in nature), and every Collection method(applied in chaining) returns an entirely new Collection instance.

e.g. We can look something like.

Collection2 = Collection1->methodOne(); // will return a new collection named Collection2
Collection3 = Collection2->methodTwo(); // will return a new Collection named Collection3

Above two lines are equivalent to a single line as below,

Collection3 = Collection1->methodOne()->methodTwo();

Collection class is able to provide many methods few of them are –

all, average, avg , chunk, collapse, combine, contains, containsStrict, count, diff, diffAssoc, diffKeys, each, every,except.


collect([1, 2, 3])->all();

// [1, 2, 3]

$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20

$average = collect([1, 1, 2, 4])->avg();

// 2

Laravel Eloquent vs Query Builder

Eloquent Models

Eloquent is Laravel’s implementation of Active Record pattern for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. and it comes with all its strengths and weaknesses. It is a good solution to use when you process a single entity in a CRUD manner – that is, read from database or create a new entity and then save it or delete. You will benefit a lot from Eloquent’s features such as dirty checking (to send SQL UPDATE only for the fields which have been changed), model events (e.g. to send administrative alert or update statistics counter when someone has created a new account), traits (timestamps, soft deletes, custom traits) eager/lazy loading etc.

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all. Also Eloquent has ton of extra features the the query builder lacks, such readability, accessors, mutators, JSON/Array conversion, hiding sensitive attributes, automatic timestamps, automatic attribute casting, softdeletes.

But, as you already know, it comes with some performance price. When you process a single or just a few records, there is nothing to worry about. But for cases when you read lots of records (e.g. for datagrids, for reports, for batch processing etc.) the plain DB is better approach.

Fluent query builder

Laravel’s database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.

The Laravel’s query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

NOTE: All methods available to Query Builder are available to Eloquent too, But method available to Eloquent Models is not available to Fluent, In short We can see Eloquent as a wrapper class over Query Builder.

CSRF Middleware in Laravel 5


Working of CSRF Middleware in Laravel 5

Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF “token” for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

The VerifyCsrfToken middleware, which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session.

Laravel 5 enables the VerifyCsrfToken middleware by default for all requests that is using webmiddleware . It works as below:

#1- Check if the request is a reading request (HEAD, GET, OPTIONS). If so, skip the check.
#2- Matches the token from the _token input or from the headers.
#3- Add a cookie with the token to each request.

This makes the CSRF check a lot more flexible. You don’t have to remember where to add you filters, just make sure that every form has a _token field. Because of #2 and #3, it will work with Ajax request without having to modify the core filter.

Note: This reminds us again that GET requests should never change state(More precisely GET Request are meant to retrieve the data from server, rather than make any kind of update to server database). The CSRF middleware assumes that it doesn’t need to check GET (or HEAD/OPTIONS) requests, because they should be safe to execute.

Checking the headers

At first, only the X-XSRF-TOKEN was checked. This used the Angular convention that the token could be read from the XSRF-TOKEN cookie. If Angular detects that cookie, it adds the token to all XHR requests.

var xsrfValue = urlIsSameOrigin(config.url)
? $browser.cookies()[‘XSRF-TOKEN’]
: undefined;
if (xsrfValue) {
reqHeaders[‘X-XSRF-TOKEN’] = xsrfValue;

While this does work great for Angular, it has a slight problem: Because the cookies in Laravel are always encrypted, the token from the cookie needs to be decrypted before it can be compared. This is not a problem for Angular, but it is a problem if you want to set the header manually for your own Javascript requests.

In Laravel 5.0.6, there is added support for a plain text X-CSRF-TOKEN header.

input('_token') ?: $request->header('X-CSRF-TOKEN');
if ( ! $token && $header = $request->header('X-XSRF-TOKEN'))
$token = $this->encrypter->decrypt($header);
return StringUtils::equals($request->session()->token(), $token);

You could now simply add a meta-tag to your section, read it with jQuery and set the XHR header:

headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

Above will set the token header for all your jQuery requests.

Hope it may be making a few more clarifications.

SCP Command use tips and tricks

scp command

What is SCP

scp stands for secure cp (copy), which means you can copy files across ssh connection(securely encrypted). It is a very secure way to copy files between computers.

It uses by default the port 22, and connect via an encrypted connection using SSH, in short it using all security setting applied for an ssh connections, for transferring data over network during copy of file from one host to another.

When copying a source file to a target file which already exists, scp will replace the contents of the target file (keeping the inode).

scp have various options, which can be specified over command line.

Few Examples of Scp Commands

Copy one single local file to a remote destination

scp [options [-r Recursively copy entire directories]] /path/to/source-file username@hostname:/path/to/destination-folder/

So, if you want to copy the file /home/user/table.csv to a remote host named and copy there to abhishek’s home folder, use this command.

scp /home/user/table.csv

Copy one single file from a remote server to your current local server

scp username@hostname:/path/to/source-file /path/to/destination-folder

example body could be similar to .
scp /home/abhishek/

You can copy multiple file from host to remote by just replacing file name with ‘directory-name/*’ options.

Copy one single file from a remote server to another remote server

With scp you can copy files between remote servers from a third server without the need to ssh into any of them, all weight lifting will be done by scp itself.

scp user1@server1:/path/to/file user2@server2:/path/to/folder/

Copy multiple files with one command

You can copy multiple files at once without having to copy all the files in a folder, or copy multiple files from different folders putting them in a space separated list.

scp file1.txt file2.txt file3.txt

Copy all files in a folder recursively to a remote server

scp -r /home/abhishek/html/*

SSH Command Tips and Tricks

ssh man

SSH is some kind of an abbreviation of Secure SHell. It is a protocol that allows secure connections between computers.

In more detail we can summarize it as, ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to replace rlogin and rsh, and provide secure encrypted communications between two untrusted hosts over an insecure network.

ssh connects and logs into the specified hostname (with optional user name). The user must prove his/her identity to the remote machine using one of several methods depending on the protocol version used.

Few Use Case Examples

Assuming you are using any Linux(Like Ubuntu etc.) You can perform ssh command over terminal.

The simplest pattern would be of SSH command as below with minimum option.

ssh yourusername@yourserverip

You will still be asked for a password. For security reasons, it is not even possible to directly specify the password in the syntax. You will always be asked interactively, unless you start configuring the server in an advanced way like (You may have added your system public key to remote system from which you are connecting, in this way you will be only asked a few question during first time login, not the password for your ssh username using which you are logging to system).

You can specify your port too while issuing ssh command, if you do not wish to use default port(22) setting, due to any of reasons.

ssh -p portno yourusername@yourserverip

Sometimes, especially in scripts, you may want to connect to the remote server, and run a single command and then exit again.

ssh yourusername@yourserverip checkinfo

Authentication Methods

The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, challenge-response authentication, and password authentication. Authentication methods are tried in the order specified above, though protocol 2 has a configuration option to change the default order: PreferredAuthentications.

Public Key based Authentication

In most of situation you may find you are using public key based Authentication.
Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. ssh implements public key authentication protocol automatically, using either the RSA or DSA algorithms.

Creating of public keys can be done using ssh-keygen command.

Command Pattern – Design Pattern

Commands gives us a way to package a piece of computation(a receiver and a set of actions) and pass it around as a first-class object.
Now, computation may be invoked long after some client application creates the command object.

The process of invoking a command may be done by a different thread. We can take this scenario and apply it to many useful applications such as schedulers, thread pools, and job queues etc.

For understanding command object, Let’s have a example of queue system in Laravel( A php framework ), Queues come to picture when you need to perform a task in background, without affecting the end user experience like as sending a bulk e-mail, or preparing a file to download that will be available after few minutes based on request of end user. In this case we just take the input from end user, what it wishes to do and without completing that request we just intimate to user that specific response will be available or done after a few minutes, mean while what application does, it stores Jobs( implementing queue system methods) or command object, in a database or some other structures depending on your driver configured for queue system.
and then in background we have set some threads that picks the command objects(JOBS) from its pool and gets executed its handle method. As all commands have implemented the Interface that is having handle method, and at time of calling its execute method it calls handle on the command object(JOB class).

We can summarize command pattern as below.

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable(undo) operations.

It enables encapsulating a request by binding together a set of actions on a specific receiver.

Singleton Pattern – Design Pattern

A Singleton pattern ensures a class has only instance, and provides a global point access to it.

For detailed overview we can have a look at below code flow, We are having a Singleton class having private constructor, that can’t be instantiated directly by outsider class using new operator. For instantiating this class we need to call class’s method.

public function callProgram () {
    neededInstance = Singleton.getInsatnce(); // will be returning object of singleton class.

public class Singleton {
    private static Singleton uniqueInstance ;

    //constructor of a class
    private Singleton() {


    public static Singleton getInsatnce() {
        if ( uniqueInstance == null) {
            synchronized (Singleton.class) {
                if ( uniqueInstance == null) {
                    uniqueInstance = new Singleton();

        return uniqueInstance;

Factory Pattern – Design Pattern

Factory Pattern Method encapsulates object creation. The factory method encapsulate object creation by letting subclasses decide what objects to create.

One thing to notice here, class being called(in our case concreteProduct) for instantiating the Object is independent of class that is calling, means to say both of them are unknown to each other, they know only the contract(in our case Product ), with which they will be interacting, Here product interface is contract that is known to both of them, but createrClass does not know that It is interacting with concreteProduct class object, it only know that object which it got from its subclass factory is of type Product, Rest information about object is encapsulated here.


class createrClass{
      function factoryMethod() ;  --> Abstract method
      function anOperation()

class concreteCreator extends createrClass{
    //implemented method (responsible for creating objects)
    function factoryMethod()


//Interface For concreteProduct class,
interface Product{


//class for Object being created by subclass(concreteCreator) method factoryMethod 
class concreteProduct implements Product{ 

All type of concreteProduct subclasses must implement this interface so that concreteCreator’s factoryMethod only has to know about Product interface type and no more info about subclass that is being instantiated to create Object of specific type

Hope it makes clear picture about factory pattern.