Pages

Tuesday, June 26, 2012

MySQL Optimization


Brilliant Video on the Typical Steps/Tools one would use in mySQL Optimisation

Monday, June 25, 2012

PHP Unit - Example Unit Test

  1. The tests for a class Class go into a class ClassTest.
  2. ClassTest inherits (most of the time) from PHPUnit_Framework_TestCase.
  3. The tests are public methods that are named test*.
    Alternatively, you can use the @test annotation in a method's docblock to mark it as a test method.
  4. Inside the test methods, assertion methods such as assertEquals() (see the section called “Assertions”) are used to assert that an actual value matches an expected value.

class StackTest extends PHPUnit_Framework_TestCase
{
    public function testPushAndPop()
    {
        $stack = array();
        $this->assertEquals(0, count($stack));
 
        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));
 
        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
}

Here's a List of the ASSERTIONS
Assertions
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertCount()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInstanceOf()
assertInternalType()
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()

Catalog of Patterns of Enterprise Application Architecture - Martin Fowler

  One of my Essential Resources on Understanding Software Design Patterns


Domain Logic Patterns: Transaction Script (110), Domain Model (116), Table Module (125), Service Layer (133).

Data Source Architectural Patterns: Table Data Gateway (144), Row Data Gateway (152), Active Record (160), Data Mapper (165).

Object-Relational Behavioral Patterns: Unit of Work (184), Identity Map (195), Lazy Load (200)

Object-Relational Structural Patterns: Identity Field (216), Foreign Key Mapping (236), Association Table Mapping (248), Dependent Mapping (262), Embedded Value (268), Serialized LOB (272), Single Table Inheritance (278), Class Table Inheritance (285), Concrete Table Inheritance (293), Inheritance Mappers (302).

Object-Relational Metadata Mapping Patterns: Metadata Mapping (306), Query Object (316), Repository (322).

Web Presentation Patterns: Model View Controller (330), Page Controller (333), Front Controller (344), Template View (350), Transform View (361), Two-Step View (365), Application Controller (379).

Distribution Patterns: Remote Facade (388), Data Transfer Object (401)

Offline Concurrency Patterns: Optimistic Offline Lock (416), Pessimistic Offline Lock (426), Coarse Grained Lock (438), Implicit Lock (449).

Session State Patterns: Client Session State (456), Server Session State (458), Database Session State (462).

Base Patterns: Gateway (466), Mapper (473), Layer Supertype (475), Separated Interface (476), Registry (480), Value Object (486), Money (488), Special Case (496), Plugin (499), Service Stub (504), Record Set (508)

REST Webservices with PHP in 3 Steps

1. Send Everything to index.php  using .htaccess 


RewriteEngine On    
RewriteBase /     

RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_FILENAME} !-d    
RewriteRule ^(.*)$ index.php/$1 [L] 

2. Figure Out What Was Requested 


class Request
{    
public $url_elements;    
public $verb;    
public $parameters;      
public function __construct()
{        
   $this->verb = $_SERVER['REQUEST_METHOD'];        
   $this->url_elements = explode('/', $_SERVER['PATH_INFO']); 

<continued below in Step 3>

3. Process Incoming Data  according to format

<continued from Step 2> 

   $this->parseIncomingParams();        

// initialise json as default format        
   $this->format = 'json';        

   if(isset($this->parameters['format']))
   {            
     $this->format = $this->parameters['format'];        
    }
        
return true;    
} //end of public function __construct()   

public function parseIncomingParams()

{        
  $parameters = array();          

// first of all, retrieve the GET vars        
  if (isset($_SERVER['QUERY_STRING']))
  {            
     parse_str($_SERVER['QUERY_STRING'], $parameters);        
   }          

// now how about PUT/POST bodies? These override what we got from GET        

  $body = file_get_contents("php://input");        
  $content_type = false;        

  if(isset($_SERVER['CONTENT_TYPE']))
   {            
      $content_type = $_SERVER['CONTENT_TYPE'];        
    }        

  switch($content_type)
   {            
     case "application/json":                
     $body_params = json_decode($body);                

     if($body_params)
      {                    
         foreach($body_params as $param_name => $param_value)
           {                        
              $parameters[$param_name] = $param_value;                    
            }                
       }                
     $this->format = "json";                
     break;            

   case "application/x-www-form-urlencoded":                
   parse_str($body, $postvars);                
   foreach($postvars as $field => $value)
     {                    
        $parameters[$field] = $value;                  
      }                
   $this->format = "html";                
   break;            

   default:               
   // we could parse other supported formats here                
   break;        
  }        //end of switch($content_type)

 $this->parameters = $parameters;
}  // end of public function parseIncomingParams()
} // end of class Request

Friday, June 22, 2012

PHP Architecture - 3 tier & MVC



Great Articles on Architecture here 

http://www.tonymarston.net/php-mysql/sample-application.html

JSON format is not safe for associative arrays

 The PHP Function json_decode() will return associative arrays as objects:
This changes things when you decode your json encoded data object.

Look at the following example I found reading a Nice Post at Stackoverflow

Here's an associative Array

$config = array(
    'Frodo'   => 'hobbit',
    'Gimli'   => 'dwarf',
    'Gandalf' => 'wizard',
    );
Lets act On It

print_r($config);
print_r(json_decode(json_encode($config)));
 
 
The Output is:

Array
(
    [Frodo] => hobbit
    [Gimli] => dwarf
    [Gandalf] => wizard)
stdClass Object
(
    [Frodo] => hobbit
    [Gimli] => dwarf
    [Gandalf] => wizard)

Difference between Abstract class and Interface

PHP 

Abstract Class Interface
Abstract methods doesn’t have any implementation. Any class that contains at least one abstract method must also be abstract Interface methods by default are abstract methods only. So one cannot declare variables or concrete methods in interfaces.
The Abstract methods can declare with Access modifiers like public, internal, protected. ' When implementing in subclass these methods must be defined with the same (or a less restricted) visibility. All methods must be public.
Abstract class can contain variables and concrete methods. Interfaces cannot contain variables and concrete methods except constants.
A class can Inherit only one Abstract class. Multiple inheritance is not possible for Abstract class. A class can implement many interfaces. Multiple interface inheritance is possible.

 


.NET
Feature
Abstract class
Interface
Multiple inheritance A class may inherit only one abstract class. A class may inherit several interfaces.
Can Provide Code Can provide complete, default code just the details that have to be overridden. Cannot provide any code, just the signature.
Access Modfiers Any access modifiers for the methods or properties Public methods only
Homogeneity Use for common behaviour Use only for shared method signatures.
Fields and Constants An abstract class can have fields and constrants defined No fields can be defined in interfaces