This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1,111 @@
---
title: Access Interceptor Scope Localizer Proxy
---
# Access Interceptor Scope Localizer Proxy
An access interceptor scope localizer is a smart reference proxy that allows you to dynamically
define logic to be executed before or after any of the proxied object's methods' logic.
It works exactly like the [access interceptor value holder](access-interceptor-value-holder.md),
with some minor differences in behavior.
The working concept of an access interceptor scope localizer is to localize scope of a proxied object:
```php
class Example
{
protected $foo;
protected $bar;
protected $baz;
public function doFoo()
{
// ...
}
}
class ExampleProxy extends Example
{
public function __construct(Example $example)
{
$this->foo = & $example->foo;
$this->bar = & $example->bar;
$this->baz = & $example->baz;
}
public function doFoo()
{
return parent::doFoo();
}
}
```
This allows to create a mirror copy of the real instance, where any change in the proxy or in the real
instance is reflected in both objects.
The main advantage of this approach is that the proxy is now safe against fluent interfaces, which
would break an [access interceptor value holder](access-interceptor-value-holder.md) instead.
## Differences with [access interceptor value holder](access-interceptor-value-holder.md):
* It does **NOT** implement the `ProxyManager\Proxy\ValueHolderInterface`, since the proxy itself
does not keep a reference to the original object being proxied
* In all interceptor methods (see [access interceptor value holder](access-interceptor-value-holder.md)),
the `$instance` passed in is the proxy itself. There is no way to gather a reference to the
original object right now, and that's mainly to protect from misuse.
## Known limitations
* It is **NOT** possible to intercept access to public properties
* It is **NOT** possible to proxy interfaces, since this proxy relies on `parent::method()` calls.
Interfaces obviously don't provide a parent method implementation.
* calling `unset` on a property of an access interceptor scope localizer (or the real instance)
will cause the two objects to be un-synchronized, with possible unexpected behaviour.
* serializing or un-serializing an access interceptor scope localizer (or the real instance)
will not cause the real instance (or the proxy) to be serialized or un-serialized
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Example
Here's an example of how you can create and use an access interceptor scope localizer :
```php
<?php
use ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory as Factory;
require_once __DIR__ . '/vendor/autoload.php';
class Foo
{
public function doFoo()
{
echo "Foo!\n";
}
}
$factory = new Factory();
$proxy = $factory->createProxy(
new Foo(),
['doFoo' => function () { echo "PreFoo!\n"; }],
['doFoo' => function () { echo "PostFoo!\n"; }]
);
$proxy->doFoo();
```
This send something like following to your output:
```
PreFoo!
Foo!
PostFoo!
```
This is pretty much the same logic that you can find
in [access interceptor value holder](access-interceptor-value-holder.md).

View File

@@ -0,0 +1,117 @@
---
title: Access Interceptor Value Holder Proxy
---
# Access Interceptor Value Holder Proxy
An access interceptor value holder is a smart reference proxy that allows you to dynamically
define logic to be executed before or after any of the wrapped object's methods
logic.
It wraps around a real instance of the object to be proxied, and can be useful for things like:
* caching execution of slow and heavy methods
* log method calls
* debugging
* event triggering
* handling of orthogonal logic, and [AOP](http://en.wikipedia.org/wiki/Aspect-oriented_programming) in general
## Example
Here's an example of how you can create and use an access interceptor value holder:
```php
<?php
use ProxyManager\Factory\AccessInterceptorValueHolderFactory as Factory;
require_once __DIR__ . '/vendor/autoload.php';
class Foo
{
public function doFoo()
{
echo "Foo!\n";
}
}
$factory = new Factory();
$proxy = $factory->createProxy(
new Foo(),
['doFoo' => function () { echo "PreFoo!\n"; }],
['doFoo' => function () { echo "PostFoo!\n"; }]
);
$proxy->doFoo();
```
This send something like following to your output:
```
PreFoo!
Foo!
PostFoo!
```
## Implementing pre- and post- access interceptors
A proxy produced by the
[`ProxyManager\Factory\AccessInterceptorValueHolderFactory`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Factory/AccessInterceptorValueHolderFactory.php)
implements the
[`ProxyManager\Proxy\AccessInterceptorValueHolderInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/AccessInterceptorValueHolderInterface.php).
Therefore, you can set an access interceptor callback by calling:
```php
$proxy->setMethodPrefixInterceptor('methodName', function () { echo 'pre'; });
$proxy->setMethodSuffixInterceptor('methodName', function () { echo 'post'; });
```
You can also listen to public properties access by attaching interceptors to `__get`, `__set`, `__isset` and `__unset`.
A prefix interceptor (executed before method logic) should have the following signature:
```php
/**
* @var object $proxy the proxy that intercepted the method call
* @var object $instance the wrapped instance within the proxy
* @var string $method name of the called method
* @var array $params sorted array of parameters passed to the intercepted
* method, indexed by parameter name
* @var bool $returnEarly flag to tell the interceptor proxy to return early, returning
* the interceptor's return value instead of executing the method logic
*
* @return mixed
*/
$prefixInterceptor = function ($proxy, $instance, $method, $params, & $returnEarly) {};
```
A suffix interceptor (executed after method logic) should have the following signature:
```php
/**
* @var object $proxy the proxy that intercepted the method call
* @var object $instance the wrapped instance within the proxy
* @var string $method name of the called method
* @var array $params sorted array of parameters passed to the intercepted
* method, indexed by parameter name
* @var mixed $returnValue the return value of the intercepted method
* @var bool $returnEarly flag to tell the proxy to return early, returning the interceptor's
* return value instead of the value produced by the method
*
* @return mixed
*/
$suffixInterceptor = function ($proxy, $instance, $method, $params, $returnValue, & $returnEarly) {};
```
## Known limitations
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](https://github.com/Ocramius/ProxyManager/blob/master/docs/tuning-for-production.md).

View File

@@ -0,0 +1,15 @@
---
title: License
---
# License
Copyright (c) 2013 Marco Pivetta
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---

View File

@@ -0,0 +1,26 @@
---
title: Credits
---
# Credits
The idea was originated by a [talk about Proxies in PHP OOP](http://marco-pivetta.com/proxy-pattern-in-php/) that I gave at the [@phpugffm](https://twitter.com/phpugffm) in January 2013.
---
### Contributors
- [Marco Pivetta](https://github.com/Ocramius)
- [Jefersson Nathan](https://github.com/malukenho)
- [Blanchon Vincent](https://github.com/blanchonvincent)
- [Markus Staab](https://github.com/staabm)
- [Gordon Stratton](https://github.com/gws)
- [Prolic](https://github.com/prolic)
- [Guillaume Royer](https://github.com/guilro)
- [Robert Reiz](https://github.com/reiz)
- [Lee Davis](https://github.com/leedavis81)
- [flip111](https://github.com/flip111)
- [Krzysztof Menzyk](https://github.com/krymen)
- [Aleksey Khudyakov](https://github.com/Xerkus)
- [Alexander](https://github.com/asm89)
- [Raul Fraile](https://github.com/raulfraile)

View File

@@ -0,0 +1,11 @@
---
title: Download / Installation
---
## Download / Installation
The suggested installation method is via [composer](https://getcomposer.org/).
```sh
php composer.phar require ocramius/proxy-manager:1.0.*
```

View File

@@ -0,0 +1,20 @@
---
title: Generator strategies
---
# Generator strategies
ProxyManager allows you to generate classes based on generator strategies and a
given `Zend\Code\Generator\ClassGenerator` as of
the [interface of a generator strategy](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/GeneratorStrategyInterface.php).
Currently, 3 generator strategies are shipped with ProxyManager:
* [`ProxyManager\GeneratorStrategy\BaseGeneratorStrategy`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/BaseGeneratorStrategy.php),
which simply retrieves the string representation of the class from `ClassGenerator`
* [`ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/EvaluatingGeneratorStrategy.php),
which calls `eval()` upon the generated class code before returning it. This is useful in cases
where you want to generate multiple classes at runtime
* [`ProxyManager\GeneratorStrategy\FileWriterGeneratorStrategy`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/FileWriterGeneratorStrategy.php),
which accepts a [`ProxyManager\FileLocator\FileLocatorInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/FileLocator/FileLocatorInterface.php)
instance as constructor parameter, and based on it, writes the generated class to a file before returning its code.

View File

@@ -0,0 +1,408 @@
---
title: Lazy Loading Ghost Object Proxies
---
# Lazy Loading Ghost Object Proxies
A Lazy Loading Ghost is a type of proxy object.
More specifically, it is a fake object that looks exactly like an object
that you want to interact with, but is actually just an empty instance
that gets all properties populated as soon as they are needed.
Those properties do not really exist until the ghost object is actually
initialized.
## Lazy loading with the Ghost Object
In pseudo-code, in userland, [lazy loading](http://www.martinfowler.com/eaaCatalog/lazyLoad.html) in a ghost object
looks like following:
```php
class MyObjectProxy
{
private $initialized = false;
private $name;
private $surname;
public function doFoo()
{
$this->init();
// Perform doFoo routine using loaded variables
}
private function init()
{
if (! $this->initialized) {
$data = some_logic_that_loads_data();
$this->name = $data['name'];
$this->surname = $data['surname'];
$this->initialized = true;
}
}
}
```
Ghost objects work similarly to virtual proxies, but since they don't wrap around a "real" instance of the proxied
subject, they are better suited for representing dataset rows.
## When do I use a ghost object?
You usually need a ghost object in cases where following applies:
* you are building a small data-mapper and want to lazily load data across associations in your object graph;
* you want to initialize objects representing rows in a large dataset;
* you want to compare instances of lazily initialized objects without the risk of comparing a proxy with a real subject;
* you are aware of the internal state of the object and are confident in working with its internals via reflection
or direct property access.
## Usage examples
[ProxyManager](https://github.com/Ocramius/ProxyManager) provides a factory that creates lazy loading ghost objects.
To use it, follow these steps:
First, define your object's logic without taking care of lazy loading:
```php
namespace MyApp;
class Customer
{
private $name;
private $surname;
// just write your business logic or generally logic
// don't worry about how complex this object will be!
// don't code lazy-loading oriented optimizations in here!
public function getName() { return $this->name; }
public function setName($name) { $this->name = (string) $name; }
public function getSurname() { return $this->surname; }
public function setSurname($surname) { $this->surname = (string) $surname; }
}
```
Then, use the proxy manager to create a ghost object of it.
You will be responsible for setting its state during lazy loading:
```php
namespace MyApp;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Proxy\GhostObjectInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingGhostFactory();
$initializer = function (
GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null; // disable initialization
// load data and modify the object here
$properties["\0MyApp\\Customer\0name"] = 'Agent';
$properties["\0MyApp\\Customer\0surname"] = 'Smith';
// you may also call methods on the object, but remember that
// the constructor was not called yet:
$ghostObject->setSurname('Smith');
return true; // confirm that initialization occurred correctly
};
$ghostObject = $factory->createProxy(\MyApp\Customer::class, $initializer);
```
You can now use your object as before:
```php
// this will work as before
echo $ghostObject->getName() . ' ' . $ghostObject->getSurname(); // Agent Smith
```
## Lazy Initialization
We use a closure to handle lazy initialization of the proxy instance at runtime.
The initializer closure signature for ghost objects is:
```php
/**
* @var object $ghostObject The instance of the ghost object proxy that is being initialized.
* @var string $method The name of the method that triggered lazy initialization.
* @var array $parameters An ordered list of parameters passed to the method that
* triggered initialization, indexed by parameter name.
* @var Closure $initializer A reference to the property that is the initializer for the
* proxy. Set it to null to disable further initialization.
* @var array $properties By-ref array with the properties defined in the object, with their
* default values pre-assigned. Keys are in the same format that
* an (array) cast of an object would provide:
* - `"\0Ns\\ClassName\0propertyName"` for `private $propertyName`
* defined on `Ns\ClassName`
* - `"\0Ns\\ClassName\0propertyName"` for `protected $propertyName`
* defined in any level of the hierarchy
* - `"propertyName"` for `public $propertyName`
* defined in any level of the hierarchy
*
* @return bool true on success
*/
$initializer = function (
\ProxyManager\Proxy\GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {};
```
The initializer closure should usually be coded like following:
```php
$initializer = function (
\ProxyManager\Proxy\GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null; // disable initializer for this proxy instance
// initialize properties (please read further on)
$properties["\0ClassName\0foo"] = 'foo';
$properties["\0ClassName\0bar"] = 'bar';
return true; // report success
};
```
### Lazy initialization `$properties` explained
The assignments to properties in this closure use unusual `"\0"` sequences.
This is to be consistent with how PHP represents private and protected properties when
casting an object to an array.
`ProxyManager` simply copies a reference to the properties into the `$properties` array passed to the
initializer, which allows you to set the state of the object without accessing any of its public
API. (This is a very important detail for mapper implementations!)
Specifically:
* `"\0Ns\\ClassName\0propertyName"` means `private $propertyName` defined in `Ns\ClassName`;
* `"\0*\0propertyName"` means `protected $propertyName` defined in any level of the class
hierarchy;
* `"propertyName"` means `public $propertyName` defined in any level of the class hierarchy.
Therefore, given this class:
```php
namespace MyNamespace;
class MyClass
{
private $property1;
protected $property2;
public $property3;
}
```
Its appropriate initialization code would be:
```php
namespace MyApp;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Proxy\GhostObjectInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingGhostFactory();
$initializer = function (
GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null;
$properties["\0MyNamespace\\MyClass\0property1"] = 'foo'; //private property of MyNamespace\MyClass
$properties["\0*\0property2"] = 'bar'; //protected property in MyClass's hierarchy
$properties["property3"] = 'baz'; //public property in MyClass's hierarchy
return true;
};
$instance = $factory->createProxy(\MyNamespace\MyClass::class, $initializer);
```
This code would initialize `$property1`, `$property2` and `$property3`
respectively to `"foo"`, `"bar"` and `"baz"`.
You may read the default values for those properties by reading the respective array keys.
Although it is possible to initialize the object by interacting with its public API, it is
not safe to do so, because the object only contains default property values since its constructor was not called.
## Proxy implementation
The
[`ProxyManager\Factory\LazyLoadingGhostFactory`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Factory/LazyLoadingGhostFactory.php)
produces proxies that implement the
[`ProxyManager\Proxy\GhostObjectInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/GhostObjectInterface.php).
At any point in time, you can set a new initializer for the proxy:
```php
$ghostObject->setProxyInitializer($initializer);
```
In your initializer, you **MUST** turn off any further initialization:
```php
$ghostObject->setProxyInitializer(null);
```
or
```php
$initializer = null; // if you use the initializer passed by reference to the closure
```
Remember to call `$ghostObject->setProxyInitializer(null);`, or to set `$initializer = null` inside your
initializer closure to disable initialization of your proxy, or else initialization will trigger
more than once.
## Triggering Initialization
A lazy loading ghost object is initialized whenever you access any of its properties.
Any of the following interactions would trigger lazy initialization:
```php
// calling a method (only if the method accesses internal state)
$ghostObject->someMethod();
// reading a property
echo $ghostObject->someProperty;
// writing a property
$ghostObject->someProperty = 'foo';
// checking for existence of a property
isset($ghostObject->someProperty);
// removing a property
unset($ghostObject->someProperty);
// accessing a property via reflection
$reflection = new \ReflectionProperty($ghostObject, 'someProperty');
$reflection->setAccessible(true);
$reflection->getValue($ghostObject);
// cloning the entire proxy
clone $ghostObject;
// serializing the proxy
$unserialized = unserialize(serialize($ghostObject));
```
A method like following would never trigger lazy loading, in the context of a ghost object:
```php
public function sayHello() : string
{
return 'Look ma! No property accessed!';
}
```
## Skipping properties (properties that should not be initialized)
In some contexts, you may want some properties to be completely ignored by the lazy-loading
system.
An example for that (in data mappers) is entities with identifiers: an identifier is usually
* lightweight
* known at all times
This means that it can be set in our object at all times, and we never need to lazy-load
it. Here is a typical example:
```php
namespace MyApp;
class User
{
private $id;
private $username;
private $passwordHash;
private $email;
private $address;
// ...
public function getId() : int
{
return $this->id;
}
}
```
If we want to skip the property `$id` from lazy-loading, we might want to tell that to
the `LazyLoadingGhostFactory`. Here is a longer example, with a more near-real-world
scenario:
```php
namespace MyApp;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Proxy\GhostObjectInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingGhostFactory();
$initializer = function (
GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null;
// note that `getId` won't initialize our proxy here
$properties["\0MyApp\\User\0username"] = $db->fetchField('users', 'username', $ghostObject->getId();
$properties["\0MyApp\\User\0passwordHash"] = $db->fetchField('users', 'passwordHash', $ghostObject->getId();
$properties["\0MyApp\\User\0email"] = $db->fetchField('users', 'email', $ghostObject->getId();
$properties["\0MyApp\\User\0address"] = $db->fetchField('users', 'address', $ghostObject->getId();
return true;
};
$proxyOptions = [
'skippedProperties' => [
"\0MyApp\\User\0id",
],
];
$instance = $factory->createProxy(User::class, $initializer, $proxyOptions);
$idReflection = new \ReflectionProperty(User::class, 'id');
$idReflection->setAccessible(true);
// write the identifier into our ghost object (assuming `setId` doesn't exist)
$idReflection->setValue($instance, 1234);
```
In this example, we pass a `skippedProperties` array to our proxy factory. Note the use of the `"\0"` parameter syntax as described above.
## Proxying interfaces
A lazy loading ghost object cannot proxy an interface directly, as it operates directly around
the state of an object. Use a [Virtual Proxy](lazy-loading-value-holder.md) for that instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,213 @@
---
title: Lazy Loading Value Holder Proxy
---
# Lazy Loading Value Holder Proxy
A lazy loading value holder proxy is a virtual proxy that wraps and lazily initializes a "real" instance of the proxied
class.
## What is lazy loading?
In pseudo-code, in userland, [lazy loading](http://www.martinfowler.com/eaaCatalog/lazyLoad.html) looks like following:
```php
class MyObjectProxy
{
private $wrapped;
public function doFoo()
{
$this->init();
return $this->wrapped->doFoo();
}
private function init()
{
if (null === $this->wrapped) {
$this->wrapped = new MyObject();
}
}
}
```
This code is problematic, and adds a lot of complexity that makes your unit tests' code even worse.
Also, this kind of usage often ends up in coupling your code with a particular
[Dependency Injection Container](http://martinfowler.com/articles/injection.html)
or a framework that fetches dependencies for you.
That way, further complexity is introduced, and some problems related
with service location raise, as I've explained
[in this article](http://ocramius.github.com/blog/zf2-and-symfony-service-proxies-with-doctrine-proxies/).
Lazy loading value holders abstract this logic for you, hiding your complex, slow, performance-impacting objects behind
tiny wrappers that have their same API, and that get initialized at first usage.
## When do I use a lazy value holder?
You usually need a lazy value holder in cases where following applies
* your object takes a lot of time and memory to be initialized (with all dependencies)
* your object is not always used, and the instantiation overhead can be avoided
## Usage examples
[ProxyManager](https://github.com/Ocramius/ProxyManager) provides a factory that eases instantiation of lazy loading
value holders. To use it, follow these steps:
First of all, define your object's logic without taking care of lazy loading:
```php
namespace MyApp;
class HeavyComplexObject
{
public function __construct()
{
// just write your business logic
// don't worry about how heavy initialization of this will be!
}
public function doFoo() {
echo 'OK!';
}
}
```
Then use the proxy manager to create a lazy version of the object (as a proxy):
```php
namespace MyApp;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\Proxy\LazyLoadingInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingValueHolderFactory();
$initializer = function (& $wrappedObject, LazyLoadingInterface $proxy, $method, array $parameters, & $initializer) {
$initializer = null; // disable initialization
$wrappedObject = new HeavyComplexObject(); // fill your object with values here
return true; // confirm that initialization occurred correctly
};
$proxy = $factory->createProxy('MyApp\HeavyComplexObject', $initializer);
```
You can now simply use your object as before:
```php
// this will just work as before
$proxy->doFoo(); // OK!
```
## Lazy Initialization
As you can see, we use a closure to handle lazy initialization of the proxy instance at runtime.
The initializer closure signature should be as following:
```php
/**
* @var object $wrappedObject the instance (passed by reference) of the wrapped object,
* set it to your real object
* @var object $proxy the instance proxy that is being initialized
* @var string $method the name of the method that triggered lazy initialization
* @var array $parameters an ordered list of parameters passed to the method that
* triggered initialization, indexed by parameter name
* @var Closure $initializer a reference to the property that is the initializer for the
* proxy. Set it to null to disable further initialization
*
* @return bool true on success
*/
$initializer = function (& $wrappedObject, $proxy, $method, array $parameters, & $initializer) {};
```
The initializer closure should usually be coded like following:
```php
$initializer = function (& $wrappedObject, $proxy, $method, array $parameters, & $initializer) {
$newlyCreatedObject = new Foo(); // instantiation logic
$newlyCreatedObject->setBar('baz') // instantiation logic
$newlyCreatedObject->setBat('bam') // instantiation logic
$wrappedObject = $newlyCreatedObject; // set wrapped object in the proxy
$initializer = null; // disable initializer
return true; // report success
};
```
The
[`ProxyManager\Factory\LazyLoadingValueHolderFactory`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Factory/LazyLoadingValueHolderFactory.php)
produces proxies that implement both the
[`ProxyManager\Proxy\ValueHolderInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/ValueHolderInterface.php)
and the
[`ProxyManager\Proxy\LazyLoadingInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/LazyLoadingInterface.php).
At any point in time, you can set a new initializer for the proxy:
```php
$proxy->setProxyInitializer($initializer);
```
In your initializer, you currently **MUST** turn off any further initialization:
```php
$proxy->setProxyInitializer(null);
```
or
```php
$initializer = null; // if you use the initializer by reference
```
## Triggering Initialization
A lazy loading proxy is initialized whenever you access any property or method of it.
Any of the following interactions would trigger lazy initialization:
```php
// calling a method
$proxy->someMethod();
// reading a property
echo $proxy->someProperty;
// writing a property
$proxy->someProperty = 'foo';
// checking for existence of a property
isset($proxy->someProperty);
// removing a property
unset($proxy->someProperty);
// cloning the entire proxy
clone $proxy;
// serializing the proxy
$unserialized = serialize(unserialize($proxy));
```
Remember to call `$proxy->setProxyInitializer(null);` to disable initialization of your proxy, or it will happen more
than once.
## Proxying interfaces
You can also generate proxies from an interface FQCN. By proxying an interface, you will only be able to access the
methods defined by the interface itself, even if the `wrappedObject` implements more methods. This will anyway save
some memory since the proxy won't contain useless inherited properties.
## Known limitations
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,101 @@
---
title: Null Object Proxy
---
# Null Object Proxy
A Null Object proxy is a [null object pattern](http://en.wikipedia.org/wiki/Null_Object_pattern) implementation.
The proxy factory creates a new object with defined neutral behavior based on an other object, class name or interface.
## What is null object proxy ?
In your application, when you can't return the object related to the request, the consumer of the model must check
for the return value and handle the failing condition gracefully, thus generating an explosion of conditionals throughout your code.
Fortunately, this seemingly-tangled situation can be sorted out simply by creating a polymorphic implementation of the
domain object, which would implement the same interface as the one of the object in question, only that its methods
wouldn't do anything, therefore offloading client code from doing repetitive checks for ugly null values when the operation
is executed.
## Usage examples
```php
class UserMapper
{
private $adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function fetchById($id) {
$this->adapter->select('users', ['id' => $id]);
if (!$row = $this->adapter->fetch()) {
return null;
}
return $this->createUser($row);
}
private function createUser(array $row) {
$user = new Entity\User($row['name'], $row['email']);
$user->setId($row['id']);
return $user;
}
}
```
If you want to remove conditionals from client code, you need to have a version of the entity conforming to the corresponding
interface. With the Null Object Proxy, you can build this object :
```php
$factory = new \ProxyManager\Factory\NullObjectFactory();
$nullUser = $factory->createProxy('Entity\User');
var_dump($nullUser->getName()); // empty return
```
You can now return a valid entity :
```php
class UserMapper
{
private $adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function fetchById($id) {
$this->adapter->select('users', ['id' => $id]);
return $this->createUser($this->adapter->fetch());
}
private function createUser($row) {
if (!$row) {
$factory = new \ProxyManager\Factory\NullObjectFactory();
return $factory->createProxy('Entity\User');
}
$user = new Entity\User($row['name'], $row['email']);
$user->setId($row['id']);
return $user;
}
}
```
## Proxying interfaces
You can also generate proxies from an interface FQCN. By proxying an interface, you will only be able to access the
methods defined by the interface itself, and like with the object, the methods are empty.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,111 @@
---
title: Remote Object Proxy
---
# Remote Object Proxy
The remote object implementation is a mechanism that enables an local object to control an other object on an other server.
Each call method on the local object will do a network call to get information or execute operations on the remote object.
## What is remote object proxy ?
A remote object is based on an interface. The remote interface defines the API that a consumer can call. This interface
must be implemented both by the client and the RPC server.
## Adapters
ZendFramework's RPC components (XmlRpc, JsonRpc & Soap) can be used easily with the remote object.
You will need to require the one you need via composer, though:
```sh
$ php composer.phar require zendframework/zend-xmlrpc:2.*
$ php composer.phar require zendframework/zend-json:2.*
$ php composer.phar require zendframework/zend-soap:2.*
```
ProxyManager comes with 3 adapters:
* `ProxyManager\Factory\RemoteObject\Adapter\XmlRpc`
* `ProxyManager\Factory\RemoteObject\Adapter\JsonRpc`
* `ProxyManager\Factory\RemoteObject\Adapter\Soap`
## Usage examples
RPC server side code (`xmlrpc.php` in your local webroot):
```php
interface FooServiceInterface
{
public function foo();
}
class Foo implements FooServiceInterface
{
/**
* Foo function
* @return string
*/
public function foo()
{
return 'bar remote';
}
}
$server = new Zend\XmlRpc\Server();
$server->setClass('Foo', 'FooServiceInterface'); // my FooServiceInterface implementation
$server->handle();
```
Client side code (proxy) :
```php
interface FooServiceInterface
{
public function foo();
}
$factory = new \ProxyManager\Factory\RemoteObjectFactory(
new \ProxyManager\Factory\RemoteObject\Adapter\XmlRpc(
new \Zend\XmlRpc\Client('https://localhost/xmlrpc.php')
)
);
$proxy = $factory->createProxy('FooServiceInterface');
var_dump($proxy->foo()); // "bar remote"
```
## Implementing custom adapters
Your adapters must implement `ProxyManager\Factory\RemoteObject\AdapterInterface` :
```php
interface AdapterInterface
{
/**
* Call remote object
*
* @param string $wrappedClass
* @param string $method
* @param array $params
*
* @return mixed
*/
public function call($wrappedClass, $method, array $params = []);
}
```
It is very easy to create your own implementation (for RESTful web services, for example). Simply pass
your own adapter instance to your factory at construction time
## Known limitations
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,28 @@
---
title: Tuning the ProxyManager for production
---
## Tuning the ProxyManager for production
By default, all proxy factories generate the required proxy classes at runtime.
Proxy generation causes I/O operations and uses a lot of reflection, so be sure to have
generated all of your proxies **before deploying your code on a live system**, or you
may experience poor performance.
You can configure ProxyManager so that it will try autoloading the proxies first.
Generating them "bulk" is not yet implemented:
```php
$config = new \ProxyManager\Configuration();
$config->setProxiesTargetDir(__DIR__ . '/my/generated/classes/cache/dir');
// then register the autoloader
spl_autoload_register($config->getProxyAutoloader());
```
Generating a classmap with all your proxy classes in it will also work perfectly.
Please note that all the currently implemented `ProxyManager\Factory\*` classes accept
a `ProxyManager\Configuration` object as optional constructor parameter. This allows for
fine-tuning of ProxyManager according to your needs.