I've got a Config
class in my application, which loads static config settings and parses them into arrays.
As I need to override some elements during runtime, I would need to access the public variable inside the Config
-class by doing this; $config->values['onelevel']['twolevel'] = 'changed';
I would like to make a method that is called override
that does this for me, but I cant get my head around what would be the best way to do it as my config files may get unknown amount of nested levels in the future.
It would be lovely to do something like $config->onelevel->twolevel = 'changed'
and let the __set magic method take care of the nesting, but from what I can tell, it isn't possible.
What would be the best way to do this?
Some time ago I needed a function that would let me access an array through string path, maybe you can make use of that:
Example:
PMA_array_write('onelevel/twolevel', $array, 'value');
I'd make a function with an indefinite amount of arguments, and use
func_get_args()
to get the arguments, from there, it's simply updating.Well, you said you parse them into array. Why not parse them into
stdObjects
and then simply do$config->onelevel->twolevel = 'changed'
as you want?:)I too have had this problem, and I solved this with this code. However it was based on API like:
Config::set('paths.command.default.foo.bar')
.It is just looping through the array and holding track of the current value with a reference variable.
You could either build a type on your own, that is providing the interface you're looking for or you go with the helper function you describe.
This is a code example of an override function Demo:
It is possible to do what you want.
This example is largly inspired by Zend_Config and the example given in the PHP docs on the ArrayAccess interface.
edit:
With one minor caveat: you need to calltoArray()
on data representing an array, to convert it to an array, as the class internally needs to covert array data to an instance of itself, to allow access with the object property operator->
:Eh, that's not really necessary anymore of course, since it implements ArrayAccess now. ;-)
/edit
edit 2:
The
Config
class can even be greatly simplified by extendingArrayObject
. As an added benefit, you can cast it to a proper array also.Example usage: