M
M
mustafo2016-07-07 09:13:42
PHP
mustafo, 2016-07-07 09:13:42

How to implement dependency-tracking and change-notification in PHP?

I want to implement "dependency-tracking" and "change-notification" between properties of different objects in PHP.
Everything should look something like this:

<?php

// Создаем объекты
$object1 = new Class1;
$object2 = new Class2;
$object3 = new Class3;

// Указываем зависимости.
$object2->prop = $object1->prop + 5;
$object3->prop = $object2->prop * 2;

// Меняем какое-то свойство
$object1->prop = 2;

// Свойства автоматически обновляются
echo $object2->prop; // -> 7
echo $object3->prop; // -> 14

That is, when a property of an object changes, all the properties of other objects that depend on it must change in real time.
What is the best way to implement this? Is there any design pattern to help accomplish this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Blyshko, 2016-07-07
@nekt

There is an opinion that you should not fence a garden with a cascading update of objects. Most likely, it will be enough to have getter properties in target objects that perform a certain function with each request to them. This approach will be much easier to maintain than tracking.
For tracking, I recommend using an event model - most likely it is in the framework, and if not, it is implemented quite simply - an event handler class is added, on which all other components depend, you can add an object pool class through which any instance is available (probably through it they are worth creating). After that, with each change of instances, they are required to report, they say, I am such and such, I have changed, a list of changed fields. And dependent classes subscribe to these events when they are created. When an event occurs, all instances subscribed to it are updated. And if there are no subscribers, the event simply drops.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question