开发者

array_pop, array_shift etc. on overloaded properties

开发者 https://www.devze.com 2023-04-01 13:03 出处:网络
I\'m in a rut and I\'m not sure why I elected for this solution. Something to do with building a simple ORM for MongoDB which has got way more complicated than I imagined. That\'s not the point though

I'm in a rut and I'm not sure why I elected for this solution. Something to do with building a simple ORM for MongoDB which has got way more complicated than I imagined. That's not the point though.

Anyway, I've got all of the document data stored in a protected $_data variable, and the magic methods __get, __set etc. all map to this array.

What I'm after is to modify overloaded variables using some of the following code:

// Dynamically push using
$model->comments += array('comment' => 'Oh hi there amigo.');

// Alternatively, to push:
array_push($model->comments, array('comment' => 'Oh hi there amigo.'));

// Plus, pop, shift, unshift etc.
array_{verb}($model->comments);

Basically, PHP is being a pain and throwing a notification saying:

 Indirect modification of overloaded property Model_Blogpost::$comments has no effect

I'm not enjoying this one bit. If this logic could go in __set and __get that would remove the need for me to make separate classes for every datatype mongo takes. At least, that's what my logic is saying now.

Does anyone know if something like this is possible? Or do we need to do our own home grown functions to sort this sort of stuff out (as a last resort)?

Thanks in advance, your confused friend.

Edit:

The PHP version is 5.3.6 and returning by reference as in &__get is a开发者_如何学运维 bit tricky — here's a quick overview of the code:

https://github.com/dynamism/Mundo/blob/develop/classes/mundo/object/core.php

Basically, __get calls get() to reduce code duplication. get() merges the loaded model data ($_data) with changed but unsaved model data ($_changed) to give the most recent data type.

It does this by flattening the original and changed data into a single dimension array dot using notation and merges the two. Mongo is so loose it's a pain. (FYI: you can use original() and changed() to get only $_data or $_changed respectively).

This means that it's not quite as simple as returning part of an array by reference. If that is the only way to do it, though, it looks like it will have to be refactored?


You may need to upgrade your PHP. This was fixed in later versions (not sure which). Works for me in 5.2.9.

If you are using a later version and it still issues notices, you'll want to ensure that you are defining __get with the signature:

public function &__get($val)


Got the same problem with Kohana and Mongo_Document class and php 5.3.6, turns out it wants to use own methods for adding values, so

$model->push('comments',array('comment' => 'Oh hi there amigo.'));

is a way to go

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号