Php – On implementing a dynamic proxy in PHP

PHP

I'm trying to implement dynamic proxies in PHP and I'm running into a problem of implementing interfaces.

My current approach to building a dynamic proxy is by having a class which uses the __call magic method. The issue is that this class implements no interface and/or extends no other class. So if I have a method which accepts only objects of a certain type through PHP type hints, I cannot pass an object of my dynamic proxy type.

One case I'm currently dealing with is a LazyLoader class, which checks the method being called to see if it should perform the loading procedure. My data source method for loading a user, instead of returning a User object, returns a LazyLoader object, which will load the user's friend list lazily. Many other data source methods will do similar things. The issue is that, there, I return a LazyLoader object and not a User object. So whenever I use a data source object to load a User object, I'll get back a LazyLoader object, which I can't pass to methods/functions which take a type hinted User parameter.

Any way to dynamically make a LazyLoader object "be a" User?

Edit: I could make several kinds of lazy loaders which extend the right class. For example, I could have a UserLazyLoader, a FinanceSheetLazyLoader and so forth. This is a possibility, but I'd like to see if I could solve this issue in a more generic way first.

Best Answer

Make a LazyLoader interface, subclass the class you want to proxy, and implement the LazyLoader interface. Reimplement all of the parent class' public methods to forward to the lazy-loaded real-instance.

Since the proxy is a subclass of the thing you are proxying, types will remain satisfied, it can be used as the thing it's proxying.

Related Topic