The following is an example that can easily be extended to define POPO classes:
PHP Code:
abstract class BaseModel {
public function toArray() {
$objectAsArray = [];
foreach ($this as $key => $value) {
$objectAsArray[$key] = $value;
}
return $objectAsArray;
}
public function toJson() {
return json_encode($this);
}
public function __set($name, $value) {
if (!property_exists($this, $name)) {
throw new Exception("$name is not a valid property of " . static::class);
}
$this->{$name} = $value;
}
public function __get($name) {
if (!property_exists($this, $name)) {
throw new Exception("$name is not a valid property of " . static::class);
}
return $this->{$name};
}
public function __construct($parameterMap = null) {
if (!$parameterMap) {
return;
}
foreach ($this as $key => $value) {
if (array_key_exists($key, $parameterMap)) {
$this->$key = $parameterMap[$key];
}
}
}
}
The way that this is constructed is that you can either create a new instance of the class without passing anything -or- by passing an associative array where the key matches the property name.
The class contains a toArray and toJson method so that the class can be easily converted without any additional code. The same thing goes with the magic getter and setter methods.
If you wanted to use this pattern in your project, the only thing you would need to do is create a class that extends this one and define your properties.
There is one caveat and this is intentional. If you pass in an invalid property to the constructor, it will simply skip it, but if you attempt to set an invalid property using the magic setter then an exception will be thrown.
Here is an example where I define a "State" class:
PHP Code:
<?php
class StatesModel extends BaseModel {
public $StateId;
public $StateName;
public $Slug;
public $StateShortName;
public $CreatedOnUtc;
public $CreatedBy;
public $ModifiedOnUtc;
public $ModifiedBy;
public $DeletedOnUtc;
}
$alabama = new StatesModel([
'StateId' => 1,
'StateName' => 'Alabama',
'Slug' => 'alabama',
'StateShortName' => 'al',
'CreatedOnUtc' => date('m/d/Y h:i:s a', time()),
'CreatedBy' => 1,
'InvalidProperty' => 'This will not set because it is in the constructor'
]);
print 'toArray(): ';
print_r($alabama->toArray());
print "\n";
print 'toJson(): ';
print $alabama->toJson();
print "\n";
print "\n";
print 'Attempting to set an invalid property';
$alabama->InvalidProperty = 'This should throw an exception';
Fiddle: https://onlinephp.io/c/711fc