Monthly Archives: August 2017

State Pattern – Design Pattern

The state pattern allows an object to alter its behavior. When its internal states changes, the object itself will appear to change its class

This pattern encapsulates states in to separate classes and delegate to the object representing current state.

Change in class is done by using composition over the base class (in our example Context Class’s property currentState)

Here, what we are trying to do is that attaching a subclass behavior based on previous actions performed on that object (In our case it will be Context class’s currentState property object assigned, that we will see in our example ).

<?php

// class being called to test our program
class Test
{
    public $context ;
    
    
    public function testnow()
    {
        $this->context = new Context;

        $this->context->requestOne();    // Could be any methods
        $this->context->requestTwo();

        print_r($this->context);
        $this->context->requestOne();    // Could be any methods

        // here you may see the changes in underlying classes on execution of any mathod 
        // if it tries to change it's current state, and change in state of current object will be responsible for changing the underlying state class.
        
    }
    
}


//Context   -- main class being called

Class Context {
    
    public State $StateA;
    public State $StateB;
    public State $StateC;
    public State ... ;// More state classes may involve depend on the behavior of game.

    public State $currentState; // depicting the current state of a Game
    
    public function __construct()
    {
         $this->StateA = new StateA($this);
         $this->StateB = new StateB($this);
         $this->StateC = new StateC($this);
         ...

         $this->currentState = new StateA($this); // suppose default state initailly
    }
    
    function requestOne()
    {
        ...
        $this->currentState->requestOne(); // will be calling the methods of 'currentState' assigned class, may be any of state classes.
    }

    function requestTwo()
    {
        ...
        $this->currentState->requestTwo(); // will be calling the methods of 'currentState' assigned class, may be any of state classes.
    }

    function requestThree()
    {
        ...
        $this->currentState->requestThree(); // will be calling the methods of 'currentState' assigned class, may be any of state classes.

    }

}



interface State
{
    // All these methods needs to be implemented by the class
    public function requestOne();
    public function requestTwo();
    public function requestThree();
} 


//Whenever there is a request made using class Context, its request mthod delegate(propagetes) to state subclass (e.g. StateA) , to handle the behavior of object.


class StateA implements State {

    public function requestOne()
    {
        ...
        ...
        //changing state classes if there needed
    }


    public function handleTwo()
    {
        ...
        ...
        //changing state classes if there needed
    }


    public function handelThree()
    {
        ...
        ...
        //changing state classes if there needed
    }

}

//Similarly for other classes like StateB, StateC, and so on..


class StateB implements State 
{
    
    // All methods similar to method StateA class methods
    // and additional methods may exist there too.
}

This kind of a pattern can be useful in designing Games especially, where an object behavior changes based on its previous operations.

Hope that make a little bit clear.

Composite Pattern – Design Pattern

Composite-pattern

Composite-pattern

Consider Iterator Pattern, this behaves very well if all items in a collection are equal kind, But it lacks when it comes to iterate over such a collection where all items or a few can contain a nested structure(Tree structure).

To traverse a tree, We need to visit every node(may contain further node or leaf) and leaf. So here we come of with another pattern named Composite Pattern. That works perfectly with Iterator pattern to make the job of Iteration simple for a client without knowing about underlying structure of every object in collection(Aggregate), whether it’s node or a leaf. In simple terms we can say that it will help to provide the interface that will be common for both nodes as well as leaf items, client has not to worry about object structure, that is being passed.

The Composite pattern allows you to compose objects into tree structure,to represent part-whole hierarchies. Composite lets treat individual objects and compositions of objects uniformly.

Here part-whole term is referring to each node(either a leaf or a node connected with other nodes as a parent)

Using composite structure, we can apply the same operation over both Composites(here NODEs) and individual(here LEAF) objects.

In short we are ignoring the difference between Composites(NODE) and individual(LEAF).

Iterator Pattern – Design Pattern

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

The iterator pattern allows traversal of elements of an aggregate without exposing the underlying implementation.

It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface and implementation, and places the responsibility where it should be.

one thing to notice here

Aggregate or Collection means just a group of objects, they might be stored in very different data structures like lists, arrays, hashmaps, vectors etc.

This pattern comes in the scenario when we have a different kind of collections, and we need to traverse over them in a different class, class separate from implementing collections data.

below is diagram explaining iterator pattern.

iterator-pattern

iterator-pattern

Anonymous function or Lambda function

An anonymous function is simply a function with no name.

A Lambda is an anonymous function that can be assigned to a variable or passed to another function as an argument. If you are familiar with other programming languages like Javascript etc., you will be very familiar with anonymous functions.

// Regular function
function dosomething () {
return “Hello there”;
}

Function can be called something like:

echo dosomething();
// Returns “Hello there”

An anonymous function has no name so you would define it like this:

// Anonymous function
function () {
return “Hello there”;
}

How to use Ananymous functions –

Because the function has no name, you can’t call it like a regular function.

// assiging to variable, Anonymous/lamda function

$dosomething = function () {
return “Hello there”;
}

// Calling Ananymous function
echo $dosomething();
// Returns “Hello there”

To use the anonymous function, we need to assign it to a variable and then call that variable as a function.

You could also pass the function to another function, like this:

// Pass Ananymous\Lambda to another regular function
function anotherfunction ($dosomething){
echo $dosomething();
}

// Calling function
anotherfunction(function(){
return “Hello there”;
});

Facade in Laravel

facede-larvel

What is Facade

Facades provide a “static” interface to classes that are available in the application’s service container(managing class dependencies and performing dependency injection(class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.) ).

Laravel facades serve as “static proxies” to underlying classes in the service container, providing the benefit of a short, expressive syntax while maintaining more flexibility(In terms of configuring class/libraries being used) than traditional static methods.

All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace.

How Facades Work

In a Laravel application, a facade is a class that provides access to an object from the service container. The machinery that makes this work is in the Facade class. Laravel’s facades, and any custom facades you create, will extend the base Illuminate\Support\Facades\Facade class.

The Facade base class makes use of the __callStatic() magic-method to defer calls from your facade to an object resolved from the container.

In the below lines , a call is made to the Laravel cache system. By looking at code, one might assume that the static method get is being called on the Cache class:

<?php

use Illuminate\Support\Facades\Cache;

function someMethod(){
    $id = 'abc'; //some key on which data is saved
    $user = Cache::get($id);
    
}

//If we look at that Illuminate\Support\Facades\Cache class, you'll see that there is no static method named get:

class Cache extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'cache'; }
}

If we look at that Illuminate\Support\Facades\Cache class, you’ll see that there is no static method named get:

Instead, the Cache facade extends the base Facade class and defines the method getFacadeAccessor(). This method’s job is to return the name of a service container binding.

When a user references any static method on the Cache facade, Laravel resolves the cache binding from the service container and runs the requested method (in this case, get) against that object.