Monday, May 23, 2016

How To Add Odd/Even Loop In Array Using PHP?

There are many ways to add odd/even loop in array using PHP. The most common and easy one I often use is the one below. With the help of following code, I can alternate the color of divs or tables or cell using odd and even classe.
$class = 'odd';  
for(.........) # no problem what kind of loop you are using(for,foreach,while,do)
{
   $class = ($class == 'even' ? 'odd' : 'even');
   #some code 
}

Ref: http://stackoverflow.com/a/15876816

Friday, May 20, 2016

Abstract, Final classes & methods and Interface in PHP

Abstract Class
Abstract classes are those classes which can not be directly initialized. Or in other word we can say that you can not create object of abstract classes. Abstract classes always created for inheritance purpose. You can only inherit abstract class in your child class.
Usually abstract class are also known as base class. We call it base class because abstract class are not the class which is available directly for creating object. It can only act as parent class of any normal class. You can use abstract class in class hierarchy. Mean one abstract class can inherit another abstract class also.

In abstract classes this is not necessary that every method should be abstract. Method in abstract class in php could be public, private, protected. You can create abstract classes in php using abstract keyword. Once you will make any class abstract in php you can not create object of that class.
abstract class abc
{
public function xyz()
{
return 1;
}
}
$a = new abc();//this will throw error in php
Above code will throw error in php.

Abstract classes in php are only for inheriting in other class.
abstract class testParent
{
public function abc()
{
//body of your funciton
}
}
class testChild extends testParent
{
public function xyz()
{
//body of your function
}
}
$a = new testChild();
In above example you are creating of testChild Class. TestChild class is inheriting testParent abstract class. So your abstract class is only available for inheritance. Main motive of creating abstract classes in php is to apply restriction of direct initialization or object creation.

Abstract method
As we know that abstract functions are those functions of abstract class which is only defined. It will be declared in your child class. You can create any method abstract using keyword abstract. You can only create abstract method either in abstract class or interface. Following is example of the abstract method implementation:
abstract class abc
{
abstract protected function f1($a , $b);
}
class xyz extends abc
{
protected function f1($name , $address)
{
echo "$name , $address";
}
}
$a = new xyz();
In class abc we have defined an abstract function f1. Now when we have inherited class abc then declared function f1. If you have an abstract method in your abstract class then once you inherit your abstract class then it is necessary to declare your abstract method. If you will not declare your abstract method then PHP will throw error in that case.

You can declare your abstract method in child class with the same visibility or less restricted visibility.
abstract class parentTest
{
abstract protected function f1();
abstract public function f2();
//abstract private function f3(); //this will trhow error
}
class childTest
{
public function f1()
{
//body of your function
}
public function f2()
{
//body of your function
}
protected function f3()
{
//body of your function
}
}
$a = new childTest();
In above code you can see that you have declare 3 function in abstract class. But private declaration of the abstract method will always throw error. Because private method is available only in the same class context. But in case of f1. This is protected. Now in child class we have defined it as public because public is less restricted than protected. And for function f2 which is already public so we have defined it as public in our child class. We have defined it public because no any visibility is less restricted than public.

Final class
A final class is a class that cannot be extended. To declare a class as final, you need to prefix the ‘class’ keyword with ‘final’. Example below.
final class BaseClass {
   public function myMethod() {
      echo "BaseClass method called";
   }
}
 
//this will cause Compile error
class DerivedClass extends BaseClass {
   public function myMethod() {
      echo "DerivedClass method called";
   }
}
 
$c = new DerivedClass();
$c->myMethod();
In the above example, BaseClass is declared as final and hence cannot be extended (inherited). DerivedClass tries to extend from BaseClass and hence the compiler will throw a compile error.

Final Method
A final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the ‘final’ keyword. Example below:
class BaseClass {
   final public function myMethod() {
      echo "BaseClass method called";
   }
}
 
class DerivedClass extends BaseClass {
   //this will cause Compile error
   public function myMethod() {
      echo "DerivedClass method called";
   }
}
 
$c = new DerivedClass();
$c->myMethod();
In the above example, DerivedClass extends from BaseClass. BaseClass has the method myMethod() declared as final and this cannot be overridden. In this case the compiler causes a compile error.

When to declare a class as final
You should declare a class as final when you think that you implementation of that class should not change in the derived class. You should do this mainly for Utility classes where you don’t want the behavior/implementation of your class to change.

When to declare a method as final
You should declare a class method as final when you think that the method you develop contains necessary functionality to support your application and any modification or change to the functionality can cause unexpected errors/bugs.

Interface in PHP
You can create interface in php using keyword interface. By implementation of interface in php class you are specifying set of the method which classes must implement. You can create interface in php using interface keyword. Rest of the things are typically identical to classes. Following is very small example of interface in php.
interface abc
{
public function xyz($b);
}
So in above code you are creating interface with name abc. Interface abc has function xyz. Whenever you will implement abc interface in your class then you have to create method with name xyz. If you will not create function xyz then it will throw error.

You can implement your interface in your class using implements keyword. Let us implement our interface abc in our class.
class test implements abc
{
public function xyz($b)
{
//your function body
}
}
You can only define method in interface with public accessibility. If you will use other than public visibility in interface then it will throw error. Also while defining method in your interface do not use abstract keyword in your methods.

You can also extend interface like class. You can extend interface in php using extends keyword.
interface template1
{
public function f1();
}
interface template2 extends template1
{
public function f2();
}
class abc implements template2
{
public function f1()
{
//Your function body
}
public function f2()
{
//your function body
}
}
So here template2 has all property of template2. So whenever you will implement template2 in your class, you have to create function of both interfaces.

You can also extend multiple interface in one interface in php.
interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
interface template3 extends template1, template2
{
public function f3();
}
class test implements template3
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
public function f3()
{
//your function body
}
}

You can also implement more than one interface in php class.
interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
class test implements template1, template2
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
}
You can not implement 2 interfaces if both share function with same name. It will throw error.

Your function parameter in class must be identical to the parameter in the interface signature. Following is example some example.
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($a)
{
echo $a;
}
}

Above will work. But following example will not work:
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1()
{
echo $a;
}
}

But it is not necessary to use the same name of the variable. Like $a. You can also use any name. For example:
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($name)
{
echo $name;
}
}

If you are using default argument then you can change your value of the argument. For example
interface template1
{
public function f1($a = 20)
}
class test implements template1
{
public function f1($name  = "ankur")
{
echo $name;
}
}


Source: http://www.techflirt.com/tutorials/oop-in-php/abstract-classes-interface.html
http://www.sunilb.com/php/php-5-tutorial-final-class-and-methods

Tuesday, May 10, 2016

DDD Building Blocks Dictionary

Domain Driven Design (DDD) is basically a bunch of concepts and components to structure your application from a business perspective. It pays attention to a project’s domain and allows collaboration between business experts and developers.

DDD consists of a lot of concepts, and you may feel overwhelmed by them at the very beginning. That's why I want to introduce you to them so that you can easily understand what is this all about.


Fig: Building blocks of domain driven design


Domain
It is a subject of matter that we are building software on. A sphere of knowledge, influence, or activity to which the user applies a software. For example, In a cafe domain, our focus will be on the concept of a tab, which tracks the visit of an individual or group to the cafe. When people arrive to the cafe and take a table, a tab is opened. They may then order drinks and food. Once the chef has prepared the food, it can then be served. Finally, the visitors close the tab by paying what is owed, possibly with a tip for the serving staff. Upon closing a tab, it must be paid for in full.

Ubiquitous language

A common, rigorous language to help communication between software developers and domain experts. A language structured around the domain model and used by all team members to connect all the activities of the team with the software.

Invariant
- It describes something that must be true with your design all the time.
- Invariants help us to discover the Bounded Context.
- An invariant is a statement about the domain that holds true, no matter what. By enforcing invariants, we ensure consistency in the domain model. This allows us to write code in all the layers that surround our model, without having to worry about this consistency.
- As an example, let's introduce an invariant that states that "A Basket can have no more than three Products".

Bounded Context

- It is a central part in DDD.
- A specific responsibility enforced by explicit boundaries. These boundaries are set by the different way we represent models. Different contexts may have completely different models of common concepts with mechanisms to map between them.
- It gives team members a clear and shared understanding of what has to be consistent and what can develop independently.
- A Bounded Context can be considered as a miniature application, containing it’s own Domain, own code and persistence mechanisms.
- Within a Bounded Context, there should be logical consistency; each Bounded Context should be independent of any other Bounded Context.
- Communication to and from a Bounded Context is done via a Context Map.

Entity
- Entities are objects that are defined by their identity, and that identity continues through time.
- A unique thing that has a life cycle and can change state. For example, a conference in a conference management system will be an entity; many of its attributes could change over time (such as its status, size, and even name), but within the system each particular conference will have its own unique identity.

Value object
- Not all objects are defined by their identity. For some objects what is important are the values of their attributes. For example, within our conference management system we do not need to assign an identity to every attendee's address (one reason is that all of the attendees from a particular organization may share the same address). All we are concerned with are the values of the attributes of an address: street, city, state, and so on.
- Value objects are usually immutable (unchanging over time).
- Sometimes in one context something is an entity while in another it is just a value object.

Services
You cannot always model everything as an object. For example, in the conference management system it may make sense to model a third-party payment processing system as a service. The system can pass the parameters required by the payment processing service and then receive a result back from the service. Notice that a common characteristic of a service is that it is stateless (unlike entities and value objects).
Services are usually implemented as regular class libraries that expose a collection of stateless methods. A service in a DDD domain model is not a web service. It communicates aggregate roots, performs complex use cases, cross aggregates transaction. An operation offered as an interface that stands alone in the model, with no encapsulated state.

Aggregate

-Whereas entities, value objects, and services are terms for the elements that DDD uses to describe things in the domain model, the terms aggregate and aggregate root relate specifically to the lifecycle and grouping of those elements.
- Aggregate is a cluster of domain objects that can be treated as a single unit to provide a specific functionality and for the purpose of data changes.
- An Aggregate has no getters, it represents its state by recording events. We use a Value Object to identify an Aggregate.
- Aggregate is not represented by its state, but by its history of Domain Events.
- Aggregates define consistency boundaries for groups of related entities; therefore, you can use an event raised by an aggregate to notify interested parties that a transaction (consistent set of updates) has taken place on that group of entities.
- Every aggregate has a unique ID; therefore, you can use that ID to record which aggregate in the system was the source of a particular event.
- Each aggregate has its own stream of events. Taken together, they can be used to compute its current state. Aggregates are completely isolated from each other.
- The first way to tell if your aggregate is right, is that you can look at each of the entities within it and ask, "Does this need to be directly accessed?" If you answer yes, then that entity is likely not a part of the aggregate.
- In summary, aggregates are the mechanism that DDD uses to manage the complex set of relationships that typically exist between the many entities and value objects in a typical domain model.

Aggregate root

- An aggregate root (also known as a root entity) is the gatekeeper object for the aggregate. All access to the objects within the aggregate must occur through the aggregate root; external entities are only permitted to hold a reference to the aggregate root, and all invariants should be checked by the aggregate root.
- An aggregate root is an entity that composes other entities (as well as its own values) by composition. It is the domain’s only entry point for data access. A heart of your domain.
- The job of an Aggregate Root is to control and encapsulate access to it’s members in such a way as to protect its invariants. Any references from outside the aggregate should only go to the aggregate root. The root can thus ensure the integrity of the aggregate as a whole.
- Another DDD principle is that an aggregate root is responsible for ensuring that the aggregated entities are always in a valid state.
- Another area where there can be confusion is in distinguishing entities from aggregates. Every aggregate has an entity acting as its aggregate root, and for lots and lots of entities the aggregate will consist of just this entity. The point is that "Customer have Orders" does not mean imply aggregation; Customer, Order and Product are all aggregate roots.

Domain Event
- A Domain Event is something that happened in the past, and that is of interest to the business.
- Domain Events is an immutable array of Domain Event objects. Once they have been initialized, there's no way to change them, there are no setters. Because events happen in the past, they cannot be changed or undone. That makes perfect sense: History can't be altered!
- Events happen in the past. For example, "the speaker was booked," "the seat was reserved," "the cash was dispensed."
- Events are notifications; they report something that has already happened to other interested parties. For example, "the customer's credit card has been billed $200" or "ten seats have been booked for conference X." Events can be processed multiple times, by multiple consumers.
- Here are sets of events we may come up with from the cafe tab scenario. TabOpened, DrinksOrdered, FoodOrdered, FoodCancelled, DrinksServed, FoodPrepared, FoodServed, TabClosed.
- Note that the events are very domain-focused.

CQRS — Command-Query Responsibility Segregation

- A common sense rather than a pattern. CQRS just separates a model into two separate parts — READ model and WRITE model.
- The separation occurs based upon whether the methods are a command or a query.
- They also can be referenced as Query model and Command model. Segregation must be clean so commands can’t return any data.
- A command is any method that mutates state and a query is any method that returns a value.
- CQRS is a simple pattern that strictly segregates the responsibility of handling command input into an autonomous system from the responsibility of handling side-effect-free query/read access on the same system.
- CQRS is not a top-level architecture. CQRS is something that happens at a much lower level.

Commands
- Commands are imperatives; they are requests for the system to perform a task or action. For example, "book two places for conference X" or "allocate speaker Y to room Z." Commands are usually processed just once, by a single recipient.
- Commands are things that indicate requests to our domain.
- A command may be accepted or rejected.
- An accepted command leads to zero or more events being emitted to incorporate new facts into the system.
- A rejected command leads to some kind of exception.
- Commands are also identified by looking for verbs. For example OpenTab, PlaceOrder, MarkFoodServed, CloseTab etc. However, they are focused around what the user considers as an operation.

Exceptions
- An important part of the modeling process is thinking about the things that can cause a command to be refused. We are expected to model these "sad paths" into exception types, just as commands and events are expressed as DTOs.
- Looking to the cafe domain scenario, we can identify three notable exceptions we need in our model: CannotCancelServedItem, TabHasUnservedItems and MustPayEnough. The names here try to explain why the command failed.

Command Bus
- The idea of a command bus is that you create command objects that represent what you want your application to do. Then, you toss it into the bus and the bus makes sure that the command object gets to where it needs to go.
- So, the command goes in -> the bus hands it off to a handler -> and then the handler actually does the job. The command essentially represents a method call to your service layer.
- The Command Bus pattern relies on 3 types of classes: Command (encapsulate our input, does simple validation on it), CommandHandler (dedicated to a single Command, does the actual logic) and CommandBus (interface allowing us to build Middlewares that calls the appropriate CommandHandle for the given Command)

Query
 — an interpreter, which is a structure of objects which can form itself into an SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way, those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place.

Event Sourcing

- Event sourcing is a way of persisting your application's state by storing the history that determines the current state of your application. For example, a conference management system needs to track the number of completed bookings for a conference so it can check whether there are still seats available when someone tries to make a new booking.
- ensuring every change to the state of an application is captured in an event object, and that these event objects are themselves stored in the sequence they were applied for the same lifetime as the application state itself.
- A method of storing business data as a sequence of modification events.

Repository
- mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
- A mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.

- pretends to be a collection of Aggregate Roots.

Source: https://blog.lelonek.me/ddd-building-blocks-for-ruby-developers-cdc6c25a80d2
http://www.cqrs.nu/tutorial/cs/01-design

Friday, April 29, 2016

Using Ghost Columns to Fix 3 Coulmn Problems in Outlook

Outlook is a notorious problem-child for email developers. One of the most commonly seen problems is that Outlook just can't handle exact widths very well. Responsive templates that are designed with two or three side-by-side columns (which stack on mobile devices) often end up stacking on Outlook as well. But with no responsive behavior, the columns don't become full width or stack directly on top of each other. Instead, they still align left and right, as they are coded to.

This problem affects Outlook 2007, Outlook 2010, Outlook 2013 and Outlook 2016 for Windows. Fortunately, there is an easy way to solve this.
We can use the "hybrid" part of fluid hybrid design to constrain these columns so they appear as intended. Hybrid tables are also sometimes called ghost tables, because they are invisible to clients other than Outlook for desktop. By creating a ghost table with two or three columns, or TDs, we can force Outlook to display the columns side-by-side no matter what. Because other clients can't "see" this code, it won't interfere with responsive behavior.

Coding ghost columns for Outlook
I have added some classes and conditional code to these elements so that you can see the main container, as well as the left and right column tables.
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Ghost Column Example</title>
  <style>

 @media only screen and (max-width: 479px) {
   .right_column, .left_column {
    width:100% !important;
    text-align: center;
    margin:0 auto !important;
   }
   .deviceWidth {
    width:300px !important;
    padding:0;
   }
  }
  </style>
  
</head>

<body>
  <table width="600" border="0" cellpadding="0" cellspacing="0" align="center" style="margin:0 auto;" class="deviceWidth">
    <tr>
      <td class="main_container">
        <!--[if (gte mso 9)|(IE)]>
           <table width="600" align="center">
            <tr>
             <td width="250">
             <![endif]-->
        <table border="0" cellpadding="0" cellspacing="0" width="250" align="left" class="left_column">
          <tr>
            <td style="padding:0px;border: 1px solid black;">
              Left Column Content
            </td>
          </tr>
        </table>
        <!--[if (gte mso 9)|(IE)]>
             </td>
             <td width="160">
             <![endif]-->
        <table border="0" cellpadding="0" cellspacing="0" width="160" align="left" class="left_column">
          <tr>
            <td style="padding:0px;border: 1px solid black;">
              Middle left Column Content
            </td>
          </tr>
        </table>
       <!--[if (gte mso 9)|(IE)]>
             </td>
             <td width="190">
             <![endif]-->
        <table border="0" cellpadding="0" cellspacing="0" width="190" align="right" class="right_column">
          <tr>
            <td style="padding:0px;border: 1px solid black;">
              Right Column Content
            </td>
          </tr>
        </table>
        <!--[if (gte mso 9)|(IE)]>
             </td>
            </tr>
           </table>
           <![endif]-->
      </td>
    </tr>
  </table>
</body>

</html>
That's it! You should now have three tables that line up perfectly in Outlook.
Source : https://www.emailonacid.com/blog/article/email-development/using-ghost-columns-to-fix-alignment-problems-in-outlook

Tuesday, April 5, 2016

Custom Alice Fixture Processor Using Symfony

Fixtures, those nice little bits of data that you can put into your database so that when you’re developing locally you actually have something to look at: like products or users or whatever else you want to play with.
I am using https://github.com/hautelook/AliceBundle, a Symfony bundle to manage fixtures with Alice and Faker.
I’ll create the DataFixtures/ORM directory inside UserBundle. And I’ll create a file called UserFixtures. Copy the contents in there and don’t forget to update your namespace and rename the class:
<?php

// src/UserBundle/DataFixtures/ORM/UserFixtures.php
namespace UserBundle\DataFixtures\ORM;

use Hautelook\AliceBundle\Doctrine\DataFixtures\AbstractLoader;
use Nelmio\Alice\Fixtures;

class UserFixtures extends AbstractLoader
{
    /**
    * {@inheritDoc}
    */
    public function getFixtures()
    {
        return  array(
                __DIR__ . '/users.yml',
        );
    }
}
The fixtures class is special because it’s already wired up to load yml files. Let’s call ours users.yml and then go ahead and create that file:

# src/UserBundle/DataFixtures/ORM/users.yml
UserBundle\Entity\user:
    user_1:
        name: Anup Shakya
        email_address: anup.shakya@example.com
        password: testing
 
Loading your Fixtures
This is a wrapper around the Doctrine fixtures library so we use the same doctrine command php app/console hautelook_alice:doctrine:fixtures:load to load fixtures.

Creating the Processor
Whenever you need to do something other than just setting simple data, you'll use a Processor, which is like a hook that's called before and after each object is saved. For example, We need to encode the password using Symfony security password encoder. This is where Processors come in.

Step 1. Create a new class. It doesn't matter where it goes, so put it inside ORM/Processor/ and call it UserProcessor. The only rule of a processor is that it needs to implement ProcessorInterface. And that means we have to have two methods: postProcess() and preProcess().

Each is passed whatever object is being saved right now, so let's just dump the class of the object:
<?php
// src/UserBundle/DataFixtures/ORM/Processor/UserProcessor.php
namespace UserBundle\DataFixtures\Processor;

use Nelmio\Alice\ProcessorInterface;
use UserBundle\Entity\User;

class UserProcessor implements ProcessorInterface
{
    protected $encoder;

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

    public function preProcess($object)
    {
        if (!$object instanceof User) {
            return;
        }

        $password = $this->encoder->encodePassword($object, $object->getPassword());
        $object->setPassword($password);
    }

    public function postProcess($object)
    {

    }
}
Given you declared a processor UserBundle\DataFixtures\Processor\UserProcessor, you have to declare it as a service with the tag hautelook_alice.alice.processor to register it:
# app/config/services.yml
services:
    alice.processor.user:
        class: UserBundle\DataFixtures\Processor\UserProcessor
        arguments: ["@security.password_encoder"]
        tags: [ { name: hautelook_alice.alice.processor } ]
Let's reload the fixtures to see what happens!
php app/console hautelook_alice:doctrine:fixtures:load
Cool! It calls preProcessor for every object. And password is encoded.

I just wanted to share this, even if some already knows about alice processors. Ref: https://knpuniversity.com/screencast/alice-fixtures