Design patterns in php

Design patterns in php

Here i’m describing few of the common design patters used in php based frameworks for web development.

1.Factory

A factory is an object used to create another objects , this is a commonly used pattern.In this a class simply creates the object of another class you want to use.

eg:


 <?php
class Automobile
{
    private $vehicleMake;
    private $vehicleModel;

    public function __construct($make, $model)
    {
        $this->vehicleMake = $make;
        $this->vehicleModel = $model;
    }

    public function getMakeAndModel()
    {
        return $this->vehicleMake . ' ' . $this->vehicleModel;
    }
}

class AutomobileFactory
{
    public static function create($make, $model)
    {
        return new Automobile($make, $model);
    }
}

// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');

print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"

2.Singleton

The concept of Singleton pattern is that restricting a class to have only one single object for it.

3.Strategy
The basic form of Strategy design pattern is achieved by taking the benefits of interface. An interface is nothing but a collection of member functions with same name in different classes with different implementations in it. In strategy design pattern interface is used as a place holder to create instances of any classes which contain the different  implementations of the methods specified in that interface so basically what happens here is that in some client classes the interface is used as parameter of a member function and that function is used to create instances of any classes which have the interface function implementations.

eg:

<?php

interface OutputInterface
{
    public function load();
}

class SerializedArrayOutput implements OutputInterface
{
    public function load()
    {
        return serialize($arrayOfData);
    }
}

class JsonStringOutput implements OutputInterface
{
    public function load()
    {
        return json_encode($arrayOfData);
    }
}

class ArrayOutput implements OutputInterface
{
    public function load()
    {
        return $arrayOfData;
    }
}


class SomeClient
{
    private $output;

    public function setOutput(OutputInterface $outputType)
    {
        $this->output = $outputType;
    }

    public function loadOutput()
    {
        return $this->output->load();
    }
}


$client = new SomeClient();

// Want an array?
$client->setOutput(new ArrayOutput());
$data = $client->loadOutput();

// Want some JSON?
$client->setOutput(new JsonStringOutput());
$data = $client->loadOutput();

4.Front Controller

The front controller pattern is where you have a single entrance point for your web application (e.g. index.php) that handles all of the requests. This code is responsible for loading all of the dependencies, processing the request and sending the response to the browser. The front controller pattern can be beneficial because it encourages modular code and gives you a central place to hook in code that should be run for every request (such as input sanitization).

 

5.Mode-View Controller (MVC)

The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objects that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats usable throughout your application. Controllers handle the request, process the data returned from models and load views to send in the response. And views are display templates (markup, xml, etc) that are sent in the response to the web browser.

#Tip to Change port of Spring boot App & Enable Auto build in Eclipse.

To change the port of the Spring boot web app you just need to add the below line inside the main function.

 System.getProperties().put( "server.port", 8083 );  //8083 port is set here
 
 eg:
 package hello;

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
    
    	   System.getProperties().put( "server.port", 8083 );  //8083 port is set here
    	 
    	   ApplicationContext ctx = SpringApplication.run(Application.class, args);
        
        System.out.println("Let's inspect the beans provided by Spring Boot:");
        
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }

}

To Enable autobuild for spring boot app to reflect the changes into the browser from eclipse you just need to make a small update in src/pom.xml


please add the below line into one of the dependency 

   <scope>runtime</scope>
eg:
         
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>runtime</scope>
        </dependency>
        

Hope this helps

Spring boot Eclipse port rebuild

Yii2 RESTful API with OAuth 2.0

image

Overview

This article is for the one’s who is already working with PHP/Yii2 or who wants to quick start developing a RESTful API using Yii2 framework with

  • OAuth 2.0 authentication
  • A developer dashboard
  • API documentation template

Here I’m sharing the Live demo and Source code of a RESTful API with OAuth2 authentication/security developed using Yii2 framework You can use this if you want to quick start developing your own custom RESTful API by skipping 95% of your scratch works. Hopefully this will save lot of your time as this API includes all the basic stuffs you need to get started.

Developer Dashboard

This API also includes a developer dashboard with the API documentation which is developed in Yii2 framework. This will be useful to manage your developers access to the API documentation.

Why Yii2?

image

It’s Fast, It’s Secure and Professional!. Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. It can reduce your development time significantly.

What is a RESTful API?

REST is an architectural style for building APIs. It stands for “Representational State Transfer”. It means when we build an API, we build it in a way that HTTP methods and URIs mean something, and the API has to respond in a way that’s expected.

Something about OAuth 2.0

The OAuth 2.0 is an authorization framework which enables a third-party application to obtain limited access to an HTTP service.

DEMO

http://yii2-rest.dockerboxes.us
Login: developer/developer

Source Code

https://github.com/sirinibin/Yii2-RESTful-API-with-OAuth2

Official Documentation

Documentation for this RESTful API can be found on the Yii2 RESTful API with OAuth2 Documenation.

Security Vulnerabilities

If you discover a security vulnerability within this API, please send an e-mail to Sirin k at sirin@nintriva.com. All security vulnerabilities will be promptly addressed.

Installation instructions

https://github.com/sirinibin/Yii2-RESTful-API-with-OAuth2

Laravel 5.5 Lumen 5.5 RESTful API with OAuth 2.0

image

Overview

This article is for the one’s who is already working with PHP/Laravel or who wants to quick start developing RESTful API with OAuth2.0 security using Laravel 5.5 Lumen 5.5.

Here I’m sharing the Live demo and Source code of a RESTful API with OAuth2 authentication/security developed using Laravel Lumen 5.5.0. You can use this if you want to quick start developing your own custom RESTful API by skipping 95% of your scratch works. Hopefully this will save lot of your time as this API includes all the basic stuffs you need to get started.

Developer Dashboard

This API also includes a developer dashboard with the API documentation which is developed in Laravel 5.5. This will be useful to manage your developers access to the API documentation.

Why Laravel Lumen?

image

In short, It’s fast, light, and easy!. Lumen eliminates all the unnecessary and heavy features in Laravel and load only components like Eloquent, middleware, authentication & authorization, …etc which keeps it light and fast. Lumen focuses on building Stateless APIs. Therefore, sessions and views are no longer included in the latest version of Lumen.

What is a RESTful API?

REST is an architectural style for building APIs. It stands for “Representational State Transfer”. It means when we build an API, we build it in a way that HTTP methods and URIs mean something, and the API has to respond in a way that’s expected.

Something about OAuth 2.0

image

The OAuth 2.0 is an authorization framework which enables a third-party application to obtain limited access to an HTTP service.

DEMO

http://laravel-lumen-rest.dockerboxes.us
Login: developer/developer

Source Code

https://github.com/sirinibin/laravel-5.5-lumen-5.5-with-OAuth2

Official Documentation

Documentation for this RESTful API can be found on the Lumen RESTful API with OAuth2 Documenation.

Security Vulnerabilities

If you discover a security vulnerability within this API, please send an e-mail to Sirin k at sirin@nintriva.com. All security vulnerabilities will be promptly addressed.

Installation instructions

https://github.com/sirinibin/laravel-5.5-lumen-5.5-with-OAuth2

– Sirin K

laravel lumen resftful APi OAuth2.0

Binary tree data structure implementation in PHP

Below you can find the implementation of binary tree data structure in php

<?php

class Node
{
    public $data;
    public $leftChild;
    public $rightChild;

    public function __construct($data)
    {
        $this->data = $data;
        $this->leftChild = null;
        $this->rightChild = null;
    }

    public function disp_data()
    {
        echo $this->data;
    }
}

class BinaryTree
{
    public $root;

    public function __construct()
    {
        $this->root = null;
    }

    /**
     * function to display the tree
     */
    public function display()
    {
        $this->display_tree($this->root);
    }

    public function display_tree($local_root)
    {
        if ($local_root == null) {
            return;
        }
        $this->display_tree($local_root->leftChild);
        echo $local_root->data."
";
        $this->display_tree($local_root->rightChild);
    }

    /**
     * function to insert a new node
     */
    public function insert($key)
    {
        $newnode = new Node($key);
        if ($this->root == null) {
            $this->root = $newnode;

            return;
        } else {
            $parent = $this->root;
            $current = $this->root;
            while (true) {
                $parent = $current;
                if ($key == ($this->find_order($key, $current->data))) {
                    $current = $current->leftChild;
                    if ($current == null) {
                        $parent->leftChild = $newnode;

                        return;
                    }//end if2
                } else {
                    $current = $current->rightChild;
                    if ($current == null) {
                        $parent->rightChild = $newnode;

                        return;
                    }
                }
            }
        }
    }

    /**
     * function to search a particular Node
     */
    public function find($key)
    {
        $current = $this->root;
        while ($current->data != $key) {
            if ($key == $this->find_order($key, $current->data)) {
                $current = $current->leftChild;
            } else {
                $current = $current->rightChild;
            }
            if ($current == null) {
                return (null);
            }
        }

        return ($current->data);
    }

    public function delete1($key)
    {
        $current = $this->root;
        $parent = $this->root;

        $isLeftChild = true;
        while ($current->data != $key) {
            $parent = $current;
            if ($key == ($this->find_order($key, $current->data))) {
                $current = $current->leftChild;
                $isLeftChild = true;
            } else {
                $current = $current->rightChild;
                $isLeftChild = false;
            }
            if ($current == null) {
                return (null);
            }
        }

        echo "

Node to delete:".$current->data;
        //to delete a leaf node
        if ($current->leftChild == null && $current->rightChild == null) {
            if ($current == $this->root) {
                $this->root = null;
            } else {
                if ($isLeftChild == true) {
                    $parent->leftChild = null;
                } else {
                    $parent->rightChild = null;
                }
            }

            return ($current);
        } else { //to delete a node having a leftChild
            if ($current->rightChild == null) {
                if ($current == $this->root) {
                    $this->root = $current->leftChild;
                } else {
                    if ($isLeftChild == true) {
                        $parent->leftChild = $current->leftChild;
                    } else {
                        $parent->rightChild = $current->leftChild;
                    }
                }

                return ($current);
            } else { //to delete a node having a rightChild
                if ($current->leftChild == null) {
                    if ($current == $this->root) {
                        $this->root = $current->rightChild;
                    } else {
                        if ($isLeftChild == true) {
                            $parent->leftChild = $current->rightChild;
                        } else {
                            $parent->rightChild = $current->rightChild;
                        }
                    }

                    return ($current);
                } else { //to delete a node having both childs
                    $successor = $this->get_successor($current);
                    if ($current == $this->root) {
                        $this->root = $successor;
                    } else {
                        if ($isLeftChild == true) {
                            $parent->leftChild = $successor;
                        } else {
                            $parent->rightChild = $successor;
                        }
                    }
                    $successor->leftChild = $current->leftChild;

                    return ($current);
                }
            }
        }
    }

    /**
     * Function to find the successor node
     */
    public function get_successor($delNode)
    {
        $succParent = $delNode;
        $successor = $delNode;
        $temp = $delNode->rightChild;
        while ($temp != null) {
            $succParent = $successor;
            $successor = $temp;
            $temp = $temp->leftChild;
        }

        if ($successor != $delNode->rightChild) {
            $succParent->leftChild = $successor->rightChild;
            $successor->rightChild = $delNode->rightChild;
        }

        return ($successor);
    }

    /**
     * function to find the order of two strings
     */
    public function find_order($str1, $str2)
    {
        $str1 = strtolower($str1);
        $str2 = strtolower($str2);
        $i = 0;
        $j = 0;

        $p1 = $str1[$i];
        $p2 = $str2[$j];
        while (true) {
            if (ord($p1) < ord($p2) || ($p1 == '' && $p2 == '')) {
                return ($str1);
            } else {
                if (ord($p1) == ord($p2)) {
                    $p1 = $str1[++$i];
                    $p2 = $str2[++$j];
                    continue;
                }

                return ($str2);
            }
        }
    }

    public function is_empty()
    {
        return $this->root === null;
    }
}

Installing AWS CLI on Mac OS Sierra 10.12.6 for using AWS Docker Container Service

You will be needing AWS CLI when you try to use AWS Container service,and for this you need to do an authentication through command line to push your docker images into AWS repositories. So you can easily achieve that by following the below simple steps.

$ curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
$ unzip awscli-bundle.zip

$ sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
$ aws configure

WS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json

Set up Multi – node Cassandra3.6 Cluster on Ubuntu 16.04

In the below example i’m using 3 nodes with the below IP’s.Each of them have Single node cassandra cluster already set up in it.

Node1: 172.16.167.176
Node2: 172.16.167.132
Node3: 172.16.167.185

Through the below simple steps im trying to set up the nodes to function as a multi node cassandra cluster so please run the below steps in all of your available nodes in your cluster.

   Step1:Stop Cassandra daemon & delete the default data set
     $ sudo service cassandra stop
     $ sudo rm -rf /var/lib/cassandra/data/system/*   
   Step2:COnfigure the cassandra cluster using the configuration file
   
   $ sudo vim  /etc/cassandra/cassandra.yaml
   
   cluster_name: 'CassandraDOCluster'
   
   seed_provider:
  - class_name: org.apache.cassandra.locator.SimpleSeedProvider
    parameters:
         - seeds: "172.16.167.176,72.16.167.132,72.16.167.185"
  listen_address: 172.16.167.176
  rpc_address: 172.16.167.176
  endpoint_snitch: GossipingPropertyFileSnitch
  auto_bootstrap: false
   Step3:Start cassndra server & check status
   $ sudo service cassandra start
   $ sudo nodetool status   

imageStep4:Log into your node’s CQL console and try make some changes in your Db tables just to check those changes are reflecting in your other nodes too. $ cqlsh 172.16.167.176 9042

You are done.
Note: You can log into the CQL console and check the db changes you makes are reflecting in your other nodes instantly.


Set up Jenkins on Ubuntu 16.04

You can set up Jenkins on ubuntu 16.04 by following below simple steps.

   Step1: Add the repository key to the system
     
     $ wget -q -O - https://pkg.jenkins.io/debian/jenkins-ci.org.key | sudo apt-key add -
     
   Step2: Append the debian package repository address to the server's source.list
    
    $ echo deb http://pkg.jenkins.io/debian-stable binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list
    
    $ sudo apt-get update
    
   Step3:Install jenkins
   
    $ sudo apt-get install jenkins
    
   Step4:Start Jenkins
    
    $ sudo systemctl start jenkins
    $ sudo systemctl status jenkins
   
   Step5: Open firewall for the 8080 port which is default for jenkins.
   
    $ sudo ufw allow 8080
    $ sudo ufw status
    
   Step6: Setting up Jenkins:-Access your server URL with 8080 port and enter Authentication password by entering the below command.
       
    URL:http://ip_address_or_domain_name:8080
    Obtain password by running below command
    
    $ sudo cat /var/lib/jenkins/secrets/initialAdminPassword      

You are done.
Now you can continue by choosing “Install Suggested Plugins” then create and admin accounnt.

Hiding index.php from URL path of Yii2 Advanced template

Step1: Update file frontend/config/main.php and backend/config/main.php

'urlManager' => [
'class' => 'yii\web\UrlManager',
'showScriptName' => false,
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],

Step2: add .htaccess file in both frontend/web and backend/web

RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
Note: Make sure mode_rewrite module is enable in apache settings.