2

Suppose I'd like to build a database abstraction layer, which uses a lazy loading mechanism.

If I ask the layer to load a root object, it loads its external representation and constructs itself.

It then somehow identifies that certain linked objects exist. Since it might be costly to load all up-front, it established proxies for related objects. Such proxies should be able to get passed around.

If a first message is called on such a proxy, it loads its external representation and constructs itself. Since references to the proxy may have been passed around, the created object needs to replace the existing proxy-object in-place.

Can I in-place replace an object with another object in PHP?

ScottMcGready
  • 1,612
  • 2
  • 24
  • 33
SteAp
  • 11,853
  • 10
  • 53
  • 88
  • Please give a few example code snippets. Replacing `$this = new obj` is not possible, but it sounds like real `&` references on the related objects might be applicable for once. But generic proxy/interception objects would be an option too, depending on complexity. – mario May 10 '11 at 21:17
  • I wonder, that & might not be a solution - since references in PHP aren't references as found e.g. in C. I'll probably add code tomorrow. It's too late today. – SteAp May 10 '11 at 22:11

1 Answers1

2

I don't believe it's possible for an object to replace all references to itself with another object. Instead, have your proxy objects forward property access and method invocation using overloading. Implement proxying on a base proxy object (named e.g. OOProxy), then extend this to a LazyProxy class that lazily loads the proxied object. As long as you don't need to examine the type of the object, anything that has a reference to the proxy won't be able to distinguish it from the proxied.

outis
  • 75,655
  • 22
  • 151
  • 221
  • Thx! Yes, using an the proxy like an adaptor for the real objects would be the standard approach. – SteAp May 10 '11 at 22:09
  • 1
    it is possible as long as you always use references and don't use new. With that said it's a dirty hack and should be avoided in practice... see : [autoboxing with PHP](http://bit.ly/eSuuzJ)... – ircmaxell May 10 '11 at 23:40