PHP facade pattern object reuse

57 Views Asked by At

for performance reasons, im trying to reuse facade object which is passed to provided handler, there is a simplified demonstration of what im trying to achieve:

class A
{
  public $b,$f;
  function __construct($f)
  {
    $this->b = new B($this);
    $this->f = $f;
  }
  function invoke()
  {
    ($this->f)(new B($this, 1)); # this works
    ($this->f)($this->b->set(1)); # this fails
  }
}
class B
{
  function __construct(
    private $a,
    private $i=0
  ) {}
  protected function set(int $i): self
  {
    $this->i = $i;
    return $this;
  }
  function get() {
    return $this->i;
  }
}
$a = new A(function(object $b) {
  $b->get();# OK
  $b->set(2);# FAIL, kind of protected
});
$a->invoke();

i tried inheriting both classes from an empty abstract object, but without luck.

im expecting that there is some language feature that makes friendly objects or approach im unaware of.

0

There are 0 best solutions below