Thursday, 4 December 2014
Monday, 24 November 2014
Thursday, 20 November 2014
Write SQL Query in ZF2
<?phpuse Zend\Db\Sql\Select;// basic table$select0 = new Select;$select0->from('foo');// 'SELECT "foo".* FROM "foo"';// table as TableIdentifier$select1 = new Select;$select1->from(new TableIdentifier('foo', 'bar'));// 'SELECT "bar"."foo".* FROM "bar"."foo"';// table with alias$select2 = new Select;$select2->from(array('f' => 'foo'));// 'SELECT "f".* FROM "foo" AS "f"';// table with alias with table as TableIdentifier$select3 = new Select;$select3->from(array('f' => new TableIdentifier('foo')));// 'SELECT "f".* FROM "foo" AS "f"';// columns$select4 = new Select;$select4->from('foo')->columns(array('bar', 'baz'));// 'SELECT "foo"."bar" AS "bar", "foo"."baz" AS "baz" FROM "foo"';// columns with AS associative array$select5 = new Select;$select5->from('foo')->columns(array('bar' => 'baz'));// 'SELECT "foo"."baz" AS "bar" FROM "foo"';// columns with AS associative array mixed$select6 = new Select;$select6->from('foo')->columns(array('bar' => 'baz', 'bam'));// 'SELECT "foo"."baz" AS "bar", "foo"."bam" AS "bam" FROM "foo"';// columns where value is Expression, with AS$select7 = new Select;$select7->from('foo')->columns(array('bar' => new Expression('COUNT(some_column)')));// 'SELECT COUNT(some_column) AS "bar" FROM "foo"';// columns where value is Expression$select8 = new Select;$select8->from('foo')->columns(array(new Expression('COUNT(some_column) AS bar')));// 'SELECT COUNT(some_column) AS bar FROM "foo"';// columns where value is Expression with parameters$select9 = new Select;$select9->from('foo')->columns(array(new Expression('(COUNT(?) + ?) AS ?',array('some_column', 5, 'bar'),array(Expression::TYPE_IDENTIFIER, Expression::TYPE_VALUE, Expression::TYPE_IDENTIFIER))));// 'SELECT (COUNT("some_column") + ?) AS "bar" FROM "foo"';// array('column1' => 5);//// 'SELECT (COUNT("some_column") + \'5\') AS "bar" FROM "foo"';// joins (plain)$select10 = new Select;$select10->from('foo')->join('zac', 'm = n');// 'SELECT "foo".*, "zac".* FROM "foo" INNER JOIN "zac" ON "m" = "n"';// join with columns$select11 = new Select;$select11->from('foo')->join('zac', 'm = n', array('bar', 'baz'));// 'SELECT "foo".*, "zac"."bar" AS "bar", "zac"."baz" AS "baz" FROM "foo" INNER JOIN "zac" ON "m" = "n"';// join with alternate type$select12 = new Select;$select12->from('foo')->join('zac', 'm = n', array('bar', 'baz'), Select::JOIN_OUTER);// 'SELECT "foo".*, "zac"."bar" AS "bar", "zac"."baz" AS "baz" FROM "foo" OUTER JOIN "zac" ON "m" = "n"';// join with column aliases$select13 = new Select;$select13->from('foo')->join('zac', 'm = n', array('BAR' => 'bar', 'BAZ' => 'baz'));// 'SELECT "foo".*, "zac"."bar" AS "BAR", "zac"."baz" AS "BAZ" FROM "foo" INNER JOIN "zac" ON "m" = "n"';// join with table aliases$select14 = new Select;$select14->from('foo')->join(array('b' => 'bar'), 'b.foo_id = foo.foo_id');// 'SELECT "foo".*, "b".* FROM "foo" INNER JOIN "bar" AS "b" ON "b"."foo_id" = "foo"."foo_id"';// where (simple string)$select15 = new Select;$select15->from('foo')->where('x = 5');// 'SELECT "foo".* FROM "foo" WHERE x = 5';// where (returning parameters)$select16 = new Select;$select16->from('foo')->where(array('x = ?' => 5));// 'SELECT "foo".* FROM "foo" WHERE x = ?';// array('where1' => 5);//// 'SELECT "foo".* FROM "foo" WHERE x = \'5\'';// group$select17 = new Select;$select17->from('foo')->group(array('col1', 'col2'));// 'SELECT "foo".* FROM "foo" GROUP BY "col1", "col2"';$select18 = new Select;$select18->from('foo')->group('col1')->group('col2');// 'SELECT "foo".* FROM "foo" GROUP BY "col1", "col2"';$select19 = new Select;$select19->from('foo')->group(new Expression('DAY(?)', array('col1'), array(Expression::TYPE_IDENTIFIER)));// 'SELECT "foo".* FROM "foo" GROUP BY DAY("col1")';// having (simple string)$select20 = new Select;$select20->from('foo')->having('x = 5');// 'SELECT "foo".* FROM "foo" HAVING x = 5';// having (returning parameters)$select21 = new Select;$select21->from('foo')->having(array('x = ?' => 5));// 'SELECT "foo".* FROM "foo" HAVING x = ?';// array('having1' => 5);//// 'SELECT "foo".* FROM "foo" HAVING x = \'5\'';// order$select22 = new Select;$select22->from('foo')->order('c1');// 'SELECT "foo".* FROM "foo" ORDER BY "c1" ASC';// multiple order parts$select23 = new Select;$select23->from('foo')->order(array('c1', 'c2'));// 'SELECT "foo".* FROM "foo" ORDER BY "c1" ASC, "c2" ASC';// mulitple order parts$select24 = new Select;$select24->from('foo')->order(array('c1' => 'DESC', 'c2' => 'Asc')); // notice partially lower case ASC// 'SELECT "foo".* FROM "foo" ORDER BY "c1" DESC, "c2" ASC';$select25 = new Select;$select25->from('foo')->order(array('c1' => 'asc'))->order('c2 desc'); // notice partially lower case ASC// 'SELECT "foo".* FROM "foo" ORDER BY "c1" ASC, "c2" DESC';// limit$select26 = new Select;$select26->from('foo')->limit(5);// 'SELECT "foo".* FROM "foo" LIMIT ?';// array('limit' => 5);//// 'SELECT "foo".* FROM "foo" LIMIT \'5\'';// limit with offset$select27 = new Select;$select27->from('foo')->limit(5)->offset(10);// 'SELECT "foo".* FROM "foo" LIMIT ? OFFSET ?';// array('limit' => 5, 'offset' => 10);//// 'SELECT "foo".* FROM "foo" LIMIT \'5\' OFFSET \'10\'';// joins with a few keywords in the on clause$select28 = new Select;$select28->from('foo')->join('zac', '(m = n AND c.x) BETWEEN x AND y.z');// 'SELECT "foo".*, "zac".* FROM "foo" INNER JOIN "zac" ON ("m" = "n" AND "c"."x") BETWEEN "x" AND "y"."z"';// order with compound name$select29 = new Select;$select29->from('foo')->order('c1.d2');// 'SELECT "foo".* FROM "foo" ORDER BY "c1"."d2" ASC';// group with compound name$select30 = new Select;$select30->from('foo')->group('c1.d2');// 'SELECT "foo".* FROM "foo" GROUP BY "c1"."d2"';// join with expression in ON part$select31 = new Select;$select31->from('foo')->join('zac', new Expression('(m = n AND c.x) BETWEEN x AND y.z'));// 'SELECT "foo".*, "zac".* FROM "foo" INNER JOIN "zac" ON (m = n AND c.x) BETWEEN x AND y.z';// subselects$select32subselect = new Select;$select32subselect->from('bar')->where->like('y', '%Foo%');$select32 = new Select;$select32->from(array('x' => $select32subselect));// 'SELECT "x".* FROM (SELECT "bar".* FROM "bar" WHERE "y" LIKE ?) AS "x"';// 'SELECT "x".* FROM (SELECT "bar".* FROM "bar" WHERE "y" LIKE \'%Foo%\') AS "x"';// use array in where, predicate in where$select33 = new Select;$select33->from('table')->columns(array('*'))->where(array('c1' => null,'c2' => array(1, 2, 3),new \Zend\Db\Sql\Predicate\IsNotNull('c3')));// 'SELECT "table".* FROM "table" WHERE "c1" IS NULL AND "c2" IN (?, ?, ?) AND "c3" IS NOT NULL';// 'SELECT "table".* FROM "table" WHERE "c1" IS NULL AND "c2" IN (\'1\', \'2\', \'3\') AND "c3" IS NOT NULL';// Expression objects in order$select34 = new Select;$select34->from('table')->order(array(new Expression('isnull(?) DESC', array('name'), array(Expression::TYPE_IDENTIFIER)),'name'));// 'SELECT "table".* FROM "table" ORDER BY isnull("name") DESC, "name" ASC';// join with Expression object in COLUMNS part (ZF2-514)$select35 = new Select;$select35->from('foo')->columns(array())->join('bar', 'm = n', array('thecount' => new Expression("COUNT(*)")));// 'SELECT COUNT(*) AS "thecount" FROM "foo" INNER JOIN "bar" ON "m" = "n"';// multiple joins with expressions$select36 = new Select;$select36->from('foo')->join('tableA', new Predicate\Operator('id', '=', 1))->join('tableB', new Predicate\Operator('id', '=', 2))->join('tableC', new Predicate\PredicateSet(array(new Predicate\Operator('id', '=', 3),new Predicate\Operator('number', '>', 20))));// 'SELECT "foo".*, "tableA".*, "tableB".*, "tableC".* FROM "foo" '// 'INNER JOIN "tableA" ON "id" = :join1part1 INNER JOIN "tableB" ON "id" = :join2part1 '// 'INNER JOIN "tableC" ON "id" = :join3part1 AND "number" > :join3part2';//// 'SELECT "foo".*, "tableA".*, "tableB".*, "tableC".* FROM "foo" '// 'INNER JOIN "tableA" ON "id" = \'1\' INNER JOIN "tableB" ON "id" = \'2\' '// 'INNER JOIN "tableC" ON "id" = \'3\' AND "number" > \'20\'';
Friday, 14 November 2014
Design Patterns
There are numerous ways to structure the code and project for your web application,
and you can put as much or as little thought as you like into architecting.
But it is usually a good idea to follow common patterns because it will make your
code easier to manage and easier for others to understand.
Source:: Architectural pattern on Wikipedia
Source:: Software design pattern on Wikipedia
Source::Collection of implementation examples
Factory
One of the most commonly used design patterns is the factory pattern. In this pattern,a class simply creates the object you want to use. Consider the following example of
the factory pattern:
<?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"
?>
This code uses a factory to create the Automobile object. There are two possible benefits to building your code this way;
the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you will only
have to modify the code in the factory, instead of every place in your project that uses the Automobile class. The second
possible benefit is that if creating the object is a complicated job you can do all of the work in the factory, instead
of repeating it every time you want to create a new instance.
Using the factory pattern isn’t always necessary (or wise). The example code used here is so simple that a factory would
simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save
yourself a lot of trouble down the road by using factories.
Source:: Factory pattern on Wikipedia
Singleton
When designing web applications, it often makes sense conceptually and architecturally to allowaccess to one and only one instance of a particular class. The singleton pattern enables us to do this.
<?php
class Singleton
{
/**
* Returns the *Singleton* instance of this class.
*
* @staticvar Singleton $instance The *Singleton* instances of this class.
*
* @return Singleton The *Singleton* instance.
*/
public static function getInstance()
{
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
/**
* Protected constructor to prevent creating a new instance of the
* *Singleton* via the `new` operator from outside of this class.
*/
protected function __construct()
{
}
/**
* Private clone method to prevent cloning of the instance of the
* *Singleton* instance.
*
* @return void
*/
private function __clone()
{
}
/**
* Private unserialize method to prevent unserializing of the *Singleton*
* instance.
*
* @return void
*/
private function __wakeup()
{
}
}
class SingletonChild extends Singleton
{
}
$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance()); // bool(true)
$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance()); // bool(false)
var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)
?>
The code above implements the singleton pattern using a static variable and the static creation method getInstance(). Note the following:
The constructor __construct is declared as protected to prevent creating a new instance outside of the class via the new operator.
The magic method __clone is declared as private to prevent cloning of an instance of the class via the clone operator.
The magic method __wakeup is declared as private to prevent unserializing of an instance of the class via the global function unserialize().
A new instance is created via late static binding in the static creation method getInstance() with the keyword static.
This allows the subclassing of the class Singleton in the example.
The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire request
lifecycle in a web application. This typically occurs when we have global objects (such as a Configuration class) or a shared
resource (such as an event queue).
You should be wary when using the singleton pattern, as by its very nature it introduces global state into your application,
reducing testability. In most cases, dependency injection can (and should) be used in place of a singleton class.
Using dependency injection means that we do not introduce unnecessary coupling into the design of our application,
as the object using the shared or global resource requires no knowledge of a concretely defined class.
Source:: Singleton pattern on Wikipedia
Strategy
With the strategy pattern you encapsulate specific families of algorithms allowing theclient class responsible for instantiating a particular algorithm to have no knowledge of
the actual implementation. There are several variations on the strategy pattern, the
simplest of which is outlined below:
This first code snippet outlines a family of algorithms; you may want a serialized array,
some JSON or maybe just an array of data:
<?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;
}
}
?>
By encapsulating the above algorithms you are making it nice and clear in your code that other developers
can easily add new output types without affecting the client code.
You will see how each concrete ‘output’ class implements an OutputInterface - this serves two purposes,
primarily it provides a simple contract which must be obeyed by any new concrete implementations. Secondly
by implementing a common interface you will see in the next section that you can now utilise Type Hinting
to ensure that the client which is utilising these behaviours is of the correct type in this case ‘OutputInterface’.
The next snippet of code outlines how a calling client class might use one of these algorithms and
even better set the behaviour required at runtime:
<?php
class SomeClient
{
private $output;
public function setOutput(OutputInterface $outputType)
{
$this->output = $outputType;
}
public function loadOutput()
{
return $this->output->load();
}
}
?>
The calling client class above has a private property which must be set at runtime and be of type
'OutputInterface' once this property is set a call to loadOutput() will call the load() method in
the concrete class of the output type that has been set.
<?php
$client = new SomeClient();
// Want an array?
$client->setOutput(new ArrayOutput());
$data = $client->loadOutput();
// Want some JSON?
$client->setOutput(new JsonStringOutput());
$data = $client->loadOutput();
?>
More Details:: Strategy pattern on Wikipedia
Front Controller
The front controller pattern is where you have a single entrance point for you 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).
More Details:: Front Controller pattern on Wikipedia
Model-View-Controller
The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objectsthat 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.
MVC is the most common architectural pattern used in the popular PHP frameworks.
Full-Stack Frameworks
Aura
CakePHP
TYPO3 Flow [FLOW3]
FuelPHP
Joomla Framework
Laravel
Lithium
Nette Framework
Phalcon
PPI
Symfony
Yii
Zend Framework
ThinkPHP
Legacy
CodeIgniter
Kohana
Micro Frameworks
Fat-Free
MicroMVC
Silex
Slim
Respect\Rest
More Details::https://en.wikipedia.orgwiki/Comparison_of_web_application_frameworks#PHP_2
Subscribe to:
Posts (Atom)