Tag Archives: php

Facebook PHP SDK Tips

Hmm so I wrote this in November 2014… and didn’t publish it. Then found it again in November 2015. I don’t know why it was in draft – usually because there’s something horribly wrong with it. But… seems ok, and I haven’t played with the FB API since then so I doubt I can add anything (or even that it still applies) hence… PRESSING PUBLISH:

Over the last two days I’ve been at a startup event called SyncTheCity and been building a little startup called cotravel (website, twitter, facebook). One of the supposedly easy tasks was to integrate the Facebook SDK in PHP to allow facebook logins.

I blame lack of sleep and time pressure but actually this was a pain in the behind. However I have two tips for future sufferers:

1. Development Domain

Facebook will only accept requests from domains you have linked. In our case this means our live domain. We develop locally on our machines (127.0.0.1 or localhost) but you can’t register those as valid domains.

However what you can do is create an A record in your domain to 127.0.0.1 so you now have local.yourdomain.com pointing to 127.0.0.1. You can add local.yourdomain.com to facebooks’ domains for your app and off you go.

2. URL is required at both ends

The docs say you must pass a request_uri to redirect to when calling – but you must also pass the SAME uri on return or else death and room results.

This means that your two files (http://domain.com/sender.php and http://domain.com/recipient.php) must have code like:


session_start();
FacebookSession::setDefaultApplication('appid', 'appsecret');
$URL="http://domain.com/recipient.php";
$helper = new FacebookRedirectLoginHelper($URL);
$loginUrl = $helper->getLoginUrl($params);
header("Location: ".$loginUrl);

And recipient.php:


session_start();
FacebookSession::setDefaultApplication('appid', 'appsecret');
$URL="http://domain.com/recipient.php";
$helper = new FacebookRedirectLoginHelper($URL);
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
echo "Facebook Authentication Error";
} catch(\Exception $ex) {
echo "Facebook Authentication Failure";
}

Note in the above this line is the one that differs from the example:


$helper = new FacebookRedirectLoginHelper($URL);

e.g. you must pass the URL!

Long-Held HTTP Polling with AMP

Wow found this in a dark corner of a hard drive so, better late than never, here you go:

A technical working paper on the evaluation of Long-Held HTTP Polling for PHP/MySQL Architecture.

Abstract

When a web client needs to periodically refresh data held on the server there are generally two approaches. Interval polling (“short polling”), which is most commonly used, where the client repeatedly re- connects to the server for updates, and a technique in which the HTTP connection is kept open (“long polling”). Although work exists investi- gating the possibilities of long polling few if any experiments have been performed using an Apache MySQL PHP (AMP) stack. To determine the potential effectiveness of long polling with this architecture an ex- periment was designed and conducted to compare update response times using both methods with a variety of polling intervals. Results clearly show a marked improvement in timings with long polling, with the mean response time down to 0.38s compared to a mean of just under the polling interval for short polling. Issues of the complexity and load implications of wide use of long polling are discussed but were outside the remit of this experiment owing to a lack of resources.

Notes

Note that this is a just basically a subset of work performed as part of work performed for my MSc dissertation.

Links

Available from Purplepixie Labs: http://labs.purplepixie.org/content/cutting-long-held-php-2015.pdf

Purplepixie Permalink: http://go.purplepixie.org/sleepjax-long-held-http-request

 

PHPDNS SCM on GitHub.com

PHPDNS, the Purplepixie.org open source direct DNS query API for PHP, now has its development source code hosted on github.com.

Packaged releases (and release source code versions) will continue to be distributed directly from the PHPDNS web site.

The source code management (SCM) repository for development code can be found at: https://github.com/purplepixie/phpdns

All Purplepixie projects hosted on github can be found at: https://github.com/purplepixie

Variable Length Arguments in C++, Java, and PHP

Normally in software development we define methods with a given number of parameters (and their type in some languages). Quite often however we want to be able to deal with different numbers of arguments and there are two widely used approaches; different methods and default parameters.

Different methods relies on the concept that the call to function is matched not just on the name of the method but also the count (and type if applicable) of the parameters. So if we wanted a method that could accept one or two integers in C++ we could define two methods:

void SomeFunction(int);
void SomeFunction(int, int);

So if we called SomeFunction(1) the first would be used, SomeFunction(1,2) would use the second.

Default parameters allows us to define some of the parameters as optional and their default values if not passed so the definition:

void SomeMethod(int a, int b=0);

Would accept one or two integer parameters. SomeMethod(1,2) would have a=1 and b=2 whereas SomeMethod(1) would use the default value and so b=0.

This is all very good and highly useful in a variety of situations but suppose you wanted to handle any number of parameters, from a very small set (or zero) to a large number. Using either of these techniques would require a lot of additional coding, creating a method for each length or the longest set of default parameters imaginable.

This is where the concept of variable length arguments for a method comes in; we want to be able to define a method and accept an arbitrary number of arguments which it can process (please note in most if not all cases the best option for this would be to pass something like a Vector in C++ or an array in PHP, but best practice is not the point of the exercise).

Let’s consider a problem.

We want to have a LineShape function. This function takes a series of Points (a simple class just containing an X and Y coordinate). In a proper system it would then start with the first point and draw a line to each consecutive one but for our example we just want it to print a list of the points it will draw to/from in order.

This could be two points (a single line) or a complex shape of an undetermined total number of points (again note the caveat above that a Vector/List/Array would be the best and safest way to do this in TRW).

So for our implementation we need:

  • A simple Point class
  • A method (LineShape) that takes an arbitrary number of Points and prints out the coordinates
  • Code to create a set of Points and pass them to LineShape

How to do this varies from language to language and, as you might assume, it’s hardest and most dangerous in C++ (because of it’s lack of type safety), slightly easier in Java and PHP (Java because of it’s high type safety and PHP because of it’s lack of any enforced typing).

Variable Length Arguments in C++

To implement in C++ we make use of the va_ functionality provided in stdarg.h. The function is defined as taking the number of parameters passed (int) and then the parameters themselves represented by “…”.

We read the parameter count and then iterate through reading each in turn with va_arg and specifying the type to be used. Note in C++ you must specify the number of parameters being passed when calling the method.

#include <iostream>
#include <stdarg.h>
using namespace std;

// Declare the variable-length argument method
void LineShape(int, ...);

// Our simple Point class
class Point
{
public:
	int x;
	int y;
	Point(int ix, int iy)
	{
		x = ix;
		y = iy;
	}
};

// Definition of LineShape
void LineShape(int n_args, ...)
{
	va_list ap; // arg list
	va_start(ap, n_args); // start on list

	for (int i=1; i<=n_args; i++) // iterate
	{
		// read next argument as Point*
		Point* a = va_arg(ap, Point*);
		cout << a->x << "," << a->y << "\n";
	}
	va_end(ap);
}

int main(int ac, char **av)
{
	Point *a = new Point(10,10);
	Point *b = new Point(15,15);
	Point *c = new Point(10,20);
	LineShape(3, a, b, c);
	return 0;
}

There you have it in C++ (well actually using C libraries); but don’t do it (see above).

Variable Length Arguments in Java

In Java it’s a lot easier as the functionality is built-in to the language. Additionally you don’t need to pass the number of parameters and also the type is determined for the entire set of parameters (in our case Point).

Note that in order for Point to be instantiated as non-static it must be in a seperate file (Point.java).

So our Point class is:

public class Point
{
	public int x;
	public int y;
	Point(int ix, int iy)
	{
		x = ix;
		y = iy;
	}
}

And the main Var.java contains:

public class Var
{
	public static void LineShape(Point... points)
	{
		for (Point p: points)
		{
			System.out.println(p.x + "," + p.y);
		}
	}

	public static void main(String args[])
	{
		Point a = new Point(10,10);
		Point b = new Point(15,15);
		Point c = new Point(10,20);
		LineShape(a,b,c);
	}
}

So in Java we just need to declare a method with Type… name and then iterate through the array in a for loop.

Variable Length Arguments in PHP

PHP isn’t quite as built-in as Java (an actual language construct) but PHP natively provides functions to support variable length parameters to methods such as func_num_args (number of arguments) and func_get_args (arguments as an array).

<?php
class Point
{
	public $x;
	public $y;
	public function Point($ix, $iy)
	{
		$this->x = $ix;
		$this->y = $iy;
	}
}

function LineShape()
{
	$num_args = func_num_args();
	$arg_list = func_get_args();
	for ($i=0; $i < $num_args; $i++)
	{
		$point = $arg_list[$i];
		echo $point->x.",".$point->y."\n";
	}
}

$a = new Point(10,10);
$b = new Point(15,15);
$c = new Point(10,20);

LineShape($a, $b, $c);
?>

 

PHP Dynamic Factories

Design patterns are common solutions to commonly-encountered problems in software development. Of these the most widely used are creational patterns – methods of creating objects, most notably the factory pattern. The factory pattern is used for the centralised instantiation of related class objects.

Let’s illustrate this with an example using the idea of shapes. We want to have an abstract base Shape class and then concrete classes derived from the base class of specific (or concrete) shapes.

abstract class Shape
{
	abstract function Draw();
}

class Square extends Shape
{
	function Draw()
	{
		echo "Square";
	}
}

class Circle extends Shape
{
	function Draw()
	{
		echo "Circle";
	}
}

We would, without any of this factory nonsense, instantiate the classes directly:

$square = new Square();
$circle = new Circle();

Using the standard factory method rather than instantiating directly we would create classes to handle the instantiation for us. First we define an abstract ShapeFactory class and then specific concrete factories to create individual shapes. So adding to our previous code:

abstract class ShapeFactory
{
	abstract function Create();
}

class SquareFactory extends ShapeFactory
{
	function Create()
	{
		return new Square();
	}
}

class CircleFactory extends ShapeFactory
{
	function Create()
	{
		return new Circle();
	}
}

So now, rather than creating instances directly we first create a concrete factory instance and then use that to create the concrete shape:

$squareFactory = new SquareFactory();
$circleFactory = new CircleFactory();

$square = $squareFactory->Create();
$circle = $circleFactory->Create();

This is all very well and good (and design patterns in general are a very powerful and useful tool) but it fails to take advantage of PHP’s powers of runtime adaptability, the ability to change and update code behaviour and functionality during execution (at runtime).

For example having these factories provides us with a standard way to create shapes but how would we add new shapes easily. With the factory pattern we would still need code modification, new shapes require a new factory and for this factory to be explicitly used to create objects.

With the wonder that is PHP however we can be more flexible, more dynamic.

Consider the possibility we want to be able to create any type of shape from a factory.

As an example you could have a Shape Maker class which took a text string for the type and returned an appropriate object (this is known as a paramerized factory):

class ShapeMaker
{
	public function Create($type)
	{
		if ($type == "circle")
			return new Circle();
		else if ($type == "square")
			return new Square();
		else
			return null;
	}
}

This would allow the creation of shapes as follows:

$maker = new ShapeMaker();
$square = $maker->Create("square");
$circle = $maker->Create("circle");

But we would really like to go further than this; we want to create a dynamic factory, one in which shapes are simply registered with a type and a associated class name, and then created by passing the type.

For this to work we would need the following:

  • A list (array) of registered types and their class names
  • A method to register new types
  • A method to create an object of the given type
  • A fall-back; what to do if a creation request is made for a type that doesn’t exist

To make this all even easier to use in our example the class will be an abstract class using static members and methods (though of course the same idea holds true for a non-abstract class using non-static members, it would just need to be instantiated first).

So, using the same shape code but replacing the factory code with the following:

abstract class ShapeFactory
{
	protected static $types = array();

	public static function Register($type, $class)
	{
		self::$types[$type]=$class;
	}

	public static function IsRegistered($type)
	{
		if (isset(self::$types[$type]))
			return true;
		else
			return false;
	}

	public static function Create($type)
	{
		if (isset(self::$types[$type]) && 
		class_exists(self::$types[$type]))
			return new self::$types[$type];
		else
			return null;
	}
}

ShapeFactory::Register("square","Square");
ShapeFactory::Register("circle","Circle");

We create a ShapeFactory class with the ability to register, check the existence of, and create shape classes. All that remains to do is to register the Square and Circle classes with type names (the lower case versions). Once this is done they can be created with:

$square = ShapeFactory::Create("square");
$circle = ShapeFactory::Create("circle");

Which creates objects of Square and Circle using the dynamic type identifiers.

So what is the advantage of this?

Well imagine now in our code we wish to add a new shape. This shape (Triangle) is contained in a file triangle.php which may or may not be included at runtime with an include_once. We may want to limit the inclusion of triangle to an add-on pack or for just specific users, so we have logic to decide if triangle should be included.

All triangle.php needs now to contain is:

class Triangle extends Shape
{
	function Draw()
	{
		echo "Triangle";
	}
}

ShapeFactory::Register("triangle","Triangle");

And then if it is included the triangle type becomes automatically available from the ShapeFactory. If ShapeFactory had been extended (very easy) to return a list of possible shapes which was used to populate a UI component then triangle would now appear, could be selected, and used as a type identifier to create a concrete shape of the correct type (triangle) at runtime.

The idea of the dynamic factory can be taken much further with list provision or description fields for example and is with certain purplepixie.org products such as FreeDESK.

Another layer of abstraction could also easily be added; all the functionality of the ShapeFactory would be generic to any dynamic factory, just the list of types and objects being unique (if this was a non-static class these could be just different instances of a general DynamicFactory class). In the static example we create a DynamicFactory and then extend from it product-specific dynamic factories to be used to house the lists of specific types:

<?php

abstract class Shape
{
	abstract function Draw();
}

class Square extends Shape
{
	function Draw()
	{
		echo "Square";
	}
}

class Circle extends Shape
{
	function Draw()
	{
		echo "Circle";
	}
}

abstract class DynamicFactory
{
	protected static $types = array();

	public static function Register($type, $class)
	{
		self::$types[$type]=$class;
	}

	public static function IsRegistered($type)
	{
		if (isset(self::$types[$type]))
			return true;
		else
			return false;
	}

	public static function Create($type)
	{
		if (isset(self::$types[$type]) && 
		class_exists(self::$types[$type]))
			return new self::$types[$type];
		else
			return null;
	}
}

class ShapeFactory extends DynamicFactory { }

ShapeFactory::Register("square","Square");
ShapeFactory::Register("circle","Circle");

$a_square = ShapeFactory::Create("square");
$a_circle = ShapeFactory::Create("circle");

$a_square->Draw();
echo "\n";
$a_circle->Draw();
echo "\n";

?>

Some links to source files for download:

classic.php : Shows the classic factory pattern

dynamic.php : Shows the first dynamic iteration along with the maker class

dynamic2.php : Shows the finalised version