Can object methods be intercepted when they are repeated as part of a collection?

I am wondering if an object belonging to a collection class can iterate, can it be repeated and know about the collection class to which it belongs? eg.

<?php
class ExampleObject
{
    public function myMethod()
    {
        if( functionForIterationCheck() ) {
           throw new Exception('Please do not call myMethod during iteration in ' . functionToGetIteratorClass());
        }
    }
}

$collection = new CollectionClass([
    new ExampleObject,
    new ExampleObject,
    new ExampleObject
]);

foreach($collection as $item) {
    $item->myMethod(); //Exception should be thrown.
}

(new ExampleObject)->myMethod(); //No Exception thrown.

I made something from Google and didn’t find anything, I suppose it’s not possible because it breaks the main OOP somewhere, but I thought that I would ask anyway!

+6
source share
2 answers

I think we can break it down into the following problems:

  • We need to create Collectionone that is iterable.
  • Collection should

    a. hard-coded (bad) names of forbidden methods or

    .

  • , - , ,

1)

, Iterator:

class Collection implements \Iterator
{
    /**
     * @var array
     */
    private $elements;

    /**
     * @var int
     */
    private $key;

    public function __construct(array $elements)
    {
        // use array_values() here to normalize keys 
        $this->elements = array_values($elements);
        $this->key = 0;
    }

    public function current()
    {
        return $this->elements[$this->key];
    }

    public function next()
    {
        ++$this->key;
    }

    public function key()
    {
        return $this->key;
    }

    public function valid()
    {
        return array_key_exists(
            $this->key,
            $this->elements
        );
    }

    public function rewind()
    {
        $this->key = 0;
    }
}

2)

, , , :

<?php

interface HasProhibitedMethods
{
    /**
     * Returns an array of method names which are prohibited 
     * to be called when implementing class is element of a collection.
     *
     * @return string[]
     */
    public function prohibitedMethods();
}

, , .

, , :

class Element implements HasProhibitedMethods
{ 
    public function foo()
    {
        return 'foo';
    }

    public function bar()
    {
        return 'bar';
    }

    public function baz()
    {
        return 'baz';
    }

    public function prohibitedMethods()
    {
        return [
            'foo',
            'bar',
        ];
    }
}

3)

@akond, ocramius/proxymanager , , - .

Run

$ composer require ocramius/proxymanager

.

:

<?php

use ProxyManager\Factory\AccessInterceptorValueHolderFactory;

class Collection implements \Iterator
{
    /**
     * @var array
     */
    private $elements;

    /**
     * @var int
     */
    private $key;

    /**
     * @var AccessInterceptorValueHolderFactory
     */
    private $proxyFactory;

    public function __construct(array $elements)
    {
        $this->elements = array_values($elements);
        $this->key = 0;
        $this->proxyFactory = new AccessInterceptorValueHolderFactory();
    }

    public function current()
    {
        $element = $this->elements[$key];

        // if the element is not an object that implements the desired interface
        // just return it
        if (!$element instanceof HasProhibitedMethods) {
            return $element;
        }

        // fetch methods which are prohibited and should be intercepted
        $prohibitedMethods = $element->prohibitedMethods();

        // prepare the configuration for the factory, a map of method names 
        // and closures that should be invoked before the actual method will be called
        $configuration = array_combine(
            $prohibitedMethods,
            array_map(function ($prohibitedMethod) {
                // return a closure which, when invoked, throws an exception
                return function () use ($prohibitedMethod) {
                    throw new \RuntimeException(sprintf(
                        'Method "%s" can not be called during iteration',
                        $prohibitedMethod
                    ));
                };
            }, $prohibitedMethods)
        );

        return $this->proxyFactory->createProxy(
            $element,
            $configuration
        );
    }

    public function next()
    {
        ++$this->key;
    }

    public function key()
    {
        return $this->key;
    }

    public function valid()
    {
        return array_key_exists(
            $this->key,
            $this->elements
        );
    }

    public function rewind()
    {
        $this->key = 0;
    }
}

<?php

require_once __DIR__ .'/vendor/autoload.php';

$elements = [
    new Element(),
    new Element(),
    new Element(),
];

$collection = new Collection($elements);

foreach ($collection as $element) {
    $element->foo();
}

. , , Collection, , current() , .

.:

+2

, . Collection, Object. Object Collection. , Collection , "" Object s.

, -- Object s.

+1

All Articles