ts / dataobject
Simple data objects and enumerations in PHP.
This package has no released version yet, and little information is available.
README
Simple data objects and enumerations in PHP.
Requirements
All of my components require PHP >= 5.4.
Installation
Use Composer to install: composer require ts/dataobject:~2.0
Basic example
An enumeration can be used when you need to define a list of values that you ideally wanted to be able to type-hint, as in this example using the common request methods implemented in HTTP:
use TS\DataObject\Multiton\Enumeration; final class RequestMethod extends Enumeration { const CONNECT = 'CONNECT'; const DELETE = 'DELETE'; const GET = 'GET'; const HEAD = 'HEAD'; const OPTIONS = 'OPTIONS'; const POST = 'POST'; const PUT = 'PUT'; const TRACE = 'TRACE'; }
The final
keyword enforces that the enumeration cannot be extended further. Now, if you wanted to use any of those
pre-defined constants, you'd call them in this way:
function handleRequest(RequestMethod $method, ...) { ... } // Give a specific instance of the enumeration to the function $response = handleRequest(RequestMethod::GET(), ...);
Multiton example
Multitons are akin to Java's enums and can contain a lot more logic, can have their own methods, constants, etc, but still define a fixed set of instances.
Take a look at this common example using our solar system's planets:
use TS\DataObject\Multiton\Multiton; final class Planet extends Multiton { /** * Gravitational constant. * * @var float */ const G = 6.67300E-11; /** * @var float */ private $mass; /** * @var float */ private $radius; /** * Array that defines each instance's data. * * @var array */ protected static $data = [ ['MERCURY', 3.302e23, 2.4397e6], ['VENUS', 4.869e24, 6.0518e6], ['EARTH', 5.9742e24, 6.37814e6], ['MARS', 6.4191e23, 3.3972e6], ['JUPITER', 1.8987e27, 7.1492e7], ['SATURN', 5.6851e26, 6.0268e7], ['URANUS', 8.6849e25, 2.5559e7], ['NEPTUNE', 1.0244e26, 2.4764e7], // Poor Pluto =( // ['PLUTO', 1.31e22, 1.180e6], ]; /** * @param string $key * @param float $mass * @param float $radius */ protected function __construct($key, $mass, $radius) { parent::__construct($key); $this->mass = $mass; $this->radius = $radius; } /** * @return float */ public function getSurfaceGravity() { return self::G * $this->mass / ($this->radius * $this->radius); } /** * @param float $otherMass * * @return float */ public function getSurfaceWeight($mass) { return $mass * $this->getSurfaceGravity(); } }
Calculation your body's weight on another planet is now as simple as calling:
$weight = 175; $mass = $weight / Planet::EARTH()->getSurfaceGravity(); $marsWeight = Planet::MARS()->getSurfaceWeight($mass); // 66.279359