Check if an object has changed

前端 未结 5 2317
闹比i
闹比i 2021-02-19 21:31

Is there a more native way (e.x. a built-in function) with less userland code to check if an objects property values have changed instead of using one of those methods:

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 22:07

    I can offer you another solution to the problem, In fact to detect "if an object has changed" we can use observer pattern design principles. May that way should be better for some people who want to get notify about changes in object.

    Contracts/ISubject.php

    Contracts/IObserver.php

    Subject.php

    class Subject implements ISubject
    {
        public $state; // That is detector 
    
        private $observers;
    
        public function __construct()
        {
            $this->observers = new \SplObjectStorage(); // That is php built in object for testing purpose I use SplObjectStorage() to store attach()'ed objects.
        }
    
        public function attach($observer): void
        {
            echo "Subject: Attached an observer.\n";
            $this->observers->attach($observer);
        }
    
        public function detach($observer): void
        {
            $this->observers->detach($observer);
            echo "Subject: Detached an observer.\n";
        }
    
        public function notify(): void
        {
            echo "Subject: Notifying observers...\n";
            foreach ($this->observers as $observer) {
                $observer->update($this);
            }
        }
    
        public function someYourLogic()
        {
            $this->state = rand(0, 10);
            echo "Subject: My state has just changed to: {$this->state}\n";
            $this->notify();
        }
    }
    

    Observer1.php | Plus you are able to have as many ConcreteObserver as you want

    class Observer1 implements IObserver
    {
        public function update($subject): void
        {
            if ($subject->state < 5) {
                echo "Observer1: Reacted to the event.\n";
            }
        }
    }
    

    Clinet.php

    $subject = new Subject();
    
    $o1 = new Observer1();
    $subject->attach($o1);
    $subject->someYourLogic();
    

提交回复
热议问题