I need to share some associative data between different parts of my application with two requirements:
- immutability (so read-only)
- safety against mispelling or unavailable index inside the data
- mixed type
I have no need for behaviour, internal state, validation or other DDD related features, just simple read-only data.
For the past I intensively used arrays for such situations but I feel they are more prone to errors due to possible mispelling (trying to access a non existent key would just trigger a notice in standard php configuration) and easy overwriting.
So I recently came to build up a simple class that stores an associative array of data but exposes one and only one way to access it, through php built-in magic methods, throwing exceptions for undefined index inside the data and preventing clients from writing it. Code follows:
class MyData
{
protected $data;
public function __construct(array $data) {
$this->data = $data;
}
public function __get($propertyName) {
if (!array_key_exists($propertyName, $this->data)) {
throw new Exception("Missing key ".$propertyName);
}
return $this->data[$propertyName];
}
public function __set($propertyName, $value) {
throw new Exception("Cannot write ".$propertyName);
}
}
I think this approach would prevent from external writing and trying to access unavailable index, throwing related exceptions and notifying clients in a stronger way than a notice would do. Indeed this would throw an exception:
echo $data->propertyThatDoesNotExist;
and also this:
$data->propertyThatExists = $newValue;
I've already read about arrays vs objects for more or less specific purpose, such as:
- PHP: when to use arrays, and when to use objects for mostly-data-storing code constructs?
- How do I decide whether to make an Input/Output data type an array or a class?
- https://stackoverflow.com/questions/3709578/using-arrays-vs-objects-for-storing-data?noredirect=1&lq=1
- https://stackoverflow.com/questions/3193765/when-should-i-use-stdclass-and-when-should-i-use-an-array-in-php-oo-code
I am curious about what some more experienced developers (even outside of php) think about this solution, thank you very much.