What are you in the mood for today?

Tuesday, 17 April 2012

Coming from a Java background I really like the ideas of Enumerated types and when moving to PHP had a hard time accepting define(a global constant) OR constant within a class that you have to statically reference :p

So here is my enum behaviour class that was designed to be inherited into standard class is to allow for more intuitive enum coding

! This is a different way of defining enum as compared to php's SplEnum !

Let's look at how you would use it.. and then will take a look inside.

Example that represents HTTP status codes

First lets create are enum collection.

! If the code looks a bit strange with all the slashes, it's because I'm use PHP autoloader.. which I love :D !

If you want a bit more and have a good understanding of magic methods keep reading.

/**
* @note To help identify classes that cannot be instantiated we prefix them with a single underscore at the beginning
@note In order to help distinguish between variables passed into the function as against variables created inside it. We prefix the start of the variable name with an underscore.
*/
abstract class _Enumerat
{
private $value;

There the interesting stuff of how you create your enum object.As in the example above, all you need to do is call the value within the enum and add the function braces.

/**
* To help in force a standardisation on enum(as distinct from other objects) developer must invoke the enum constant value
@see _Enumerat::__callStatic(a,b)
*/
private function __construct($_value)
{
$this->value = $_value;
}
/**
* This is invoked when the you want to create an enum. it will acts like a constructor
*/
public static function __callStatic($_name, $_asString = FALSE)
{
$class = get_called_class();
$oClass = new \ReflectionClass($class);
$value = $oClass->getConstant($_name);
if(NULL === $value
OR FALSE === $value)//I'm raising an error as I consider this to be a compile time problem
{ trigger_error('invalid enum value',E_USER_ERROR); }
else
{ return new $class($value); }
}

The functions to accessing the value with in

/**
* This will convert this object instance into a string representing the enum if you try and use this object like a string
* @return string
*/
public function __toString()
{
return ''.$this();
}
/**
* This allows you to quickly and easily access the value of the enum while keeping the enum object intact
* @return mixed
*/
public function __invoke()
{
return $this->value;
}
}

Quick way to pull a list of all of the value the enum supports

/**
* This will return an array of all the predefined constants for this type of enum. The enum name will be the key and the enum's value... well, in value
* @return array
*/
public static function listValues()
{
$oClass = new \ReflectionClass(get_called_class());
return $oClass->getConstants();
}

Allows the resolving of the position of a value relative to wear it was declared.