mercredi 25 octobre 2023

PHP facade pattern object reuse

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 $test): self
  {
    $this->test = $test;
    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.

Aucun commentaire:

Enregistrer un commentaire