ProxyManager Documentation

OOP Proxy wrappers/utilities - generates and manages proxies of your objects

4,969 stars PHP PHP 1 file ยท ~9,364 tokens #aop#lazy-loading#oop#proxy
RAW Doc

1. Project Overview & Quickstart (Ocramius/ProxyManager)

File: README.md

Proxy Manager

A message to Russian ๐Ÿ‡ท๐Ÿ‡บ people

If you currently live in Russia, please read this message.

Purpose

This library aims to provide abstraction for generating various kinds of
proxy classes.




Documentation

You can learn about the proxy pattern and how to use the ProxyManager in the docs.

ocramius/proxy-manager for enterprise

Available as part of the Tidelift Subscription.

The maintainer of ocramius/proxy-manager and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more..

You can also contact the maintainer at [email protected] for looking into issues related to this package
in your private projects.

Installation

The suggested installation method is via composer:

sh
php composer.phar require ocramius/proxy-manager

Proxy example

Here's how you build a lazy loadable object with ProxyManager using a Virtual Proxy

php
$factory = new \ProxyManager\Factory\LazyLoadingValueHolderFactory();

$proxy = $factory->createProxy(
    \MyApp\HeavyComplexObject::class,
    function (& $wrappedObject, $proxy, $method, $parameters, & $initializer) {
        $wrappedObject = new \MyApp\HeavyComplexObject(); // instantiation logic here
        $initializer   = null; // turning off further lazy initialization

        return true; // report success
    }
);

$proxy->doFoo();

See the documentation for more supported proxy types and examples.


File: docs/access-interceptor-scope-localizer.md

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 methods' logic.

It works exactly like the access interceptor value holder, with some minor differences
in behaviour.

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 creating a mirror copy of the real instance, where any change in the proxy or 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 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), the $instance
    passed in is the proxy itself. There is no way to gather a reference to the original object right now, and that is 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 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 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 sends something like following to your output:

text
PreFoo!
Foo!
PostFoo!

This is similar logic to what you can find in access interceptor value holder.


File: docs/access-interceptor-value-holder.md

Access Interceptor Value Holder Proxy

An access interceptor value holder is a smart reference proxy that allows you to dynamically define the logic that will 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 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 sends something like following to your output:

text
PreFoo!
Foo!
PostFoo!

Implementing pre- and post- access interceptors

A proxy produced by the
ProxyManager\Factory\AccessInterceptorValueHolderFactory
implements the ProxyManager\Proxy\AccessInterceptorValueHolderInterface.

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 instead.

Tuning performance for production

See Tuning ProxyManager for Production.


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.


File: docs/credits.md

Credits

The idea was originated by a talk about Proxies in PHP OOP that I gave at
the @phpugffm in January 2013.

Contributors

Documentation

Gary Hockin is amazing and spent literally 20 minutes tidying up the documentation.


File: docs/download.md

Download / Installation

The suggested installation method is via Composer:

sh
composer require ocramius/proxy-manager

File: docs/generator-strategies.md

Generator strategies

ProxyManager allows you to generate classes based on generator strategies and a given Laminas\Code\Generator\ClassGenerator as of the interface of a generator strategy.

Currently, 3 generator strategies are shipped with ProxyManager:


File: docs/lazy-loading-ghost-object.md

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 just an empty
instance that gets all properties populated as soon as they are needed.

Those properties do not actually exist until the ghost object is initialized.

Lazy loading with the Ghost Object

In pseudo-code, in userland, lazy loading 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 do not 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 the 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 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 look like:

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 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 significant 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 as its constructor was not called.

Proxy implementation

The
ProxyManager\Factory\LazyLoadingGhostFactory
produces proxies that implement the
ProxyManager\Proxy\GhostObjectInterface.

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, otherwise 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
class Hello
{
    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 ignored entirely 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 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 for that instead.

Tuning performance for production

See Tuning ProxyManager for Production.


File: docs/lazy-loading-value-holder.md

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, lazy loading looks like the 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 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 or a framework that fetches dependencies
for you. That way, further complexity is introduced, and some problems related with service location raise, as explained
in this article.

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 the 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 is avoidable

Usage examples

ProxyManager provides a factory that eases instantiation of lazy loading
value holders. To use it, follow these steps:

Firstly, 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 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
produces proxies that implement both the
ProxyManager\Proxy\ValueHolderInterface
and the
ProxyManager\Proxy\LazyLoadingInterface.

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. When you proxy 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 save some memory
since the proxy will not 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 instead.

Tuning performance for production

See Tuning ProxyManager for Production.


File: docs/null-object.md

Null Object Proxy

A Null Object proxy is a null object pattern implementation.
The proxy factory creates a new object with defined neutral behaviour based on another object, class name or interface.

What is null object proxy?

In your application, when you cannot 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 simplified by creating a polymorphic implementation of the domain object,
which would implement the same interface as one of the objects in question, only that its methods would not 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.

2. Official Technical Reference & Guides (Ocramius/docs)

File: README.md

Laravel Documentation

Contribution Guidelines

If you are submitting documentation for the current stable release, submit it to the corresponding branch. For example, documentation for Laravel 4.1 would be submitted to the 4.1 branch. Documentation intended for the next release of Laravel should be submitted to the master branch.


File: Readme.md

Laravel Documentation

Contribution Guidelines

If you are submitting documentation for the current stable release, submit it to the corresponding branch. For example, documentation for Laravel 4.1 would be submitted to the 4.1 branch. Documentation intended for the next release of Laravel should be submitted to the master branch.


File: readme.md

Laravel Documentation

Contribution Guidelines

If you are submitting documentation for the current stable release, submit it to the corresponding branch. For example, documentation for Laravel 4.1 would be submitted to the 4.1 branch. Documentation intended for the next release of Laravel should be submitted to the master branch.