ED example - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of ED example.php

  1. <?php
  2.  
  3. class Event {
  4.     public $name;
  5.     public function getEvent(){
  6.         return $this->event;
  7.     }
  8. }
  9.  
  10. class SomeSubscribe {
  11.     public function process($object){
  12.         $object->property = 'MODIFIED';
  13.         return $object;
  14.     }
  15. }
  16.  
  17.  
  18. class SecondSomeSubscribe {
  19.     public function process($object){
  20.         $object->property = 'MODIFIED 2';
  21.         return $object;
  22.     }
  23. }
  24.  
  25. class SomeEvent extends Event {
  26.     const NAME = 'testEvent';
  27.     public $event;
  28.     public function __construct($event, $name){
  29.         $this->event = $event;
  30.         $this->name = $name;
  31.     }
  32. }
  33.  
  34. class EventDispatcher {
  35.     private $events;
  36.     private $subscribers;
  37.     public function addEvent(Event $event){
  38.         $this->events[$event->name] = $event;
  39.     }
  40.     public function addSubscribe($eventName, $objectSubscrube){
  41.         $this->subscribers[$eventName] = $objectSubscrube;
  42.     }
  43.     public function dispatch($name, $event=null){
  44.         $result = null;
  45.         if(null === $event){
  46.             foreach($this->subscribers as $subscribe){
  47.                 $result = $subscribe->process($this->events[$name]->getEvent());
  48.             }
  49.         } else {
  50.             foreach($this->subscribers as $subscribe){
  51.                 $result = $subscribe->process($event->getEvent());
  52.             }
  53.         }
  54.         return $result;
  55.     }
  56. }
  57.  
  58.  
  59. class ObjectEvent {
  60.     public $property;
  61.     public function getPropertyEvent(){
  62.         return $this->property;    
  63.     }
  64. }
  65.  
  66. $testEvent = new ObjectEvent();
  67. $testEvent->property = 'SOMEPROPERTY_SET_ONCE';
  68.  
  69. $dispatcher = new EventDispatcher();
  70. $dispatcher->addSubscribe(SomeEvent::NAME, new SomeSubscribe());
  71. $dispatcher->addSubscribe(SomeEvent::NAME, new SecondSomeSubscribe());
  72. $dispatcher->addEvent(new SomeEvent($testEvent, SomeEvent::NAME));
  73. $modifyObjectEvent = $dispatcher->dispatch(SomeEvent::NAME);
  74. var_dump($modifyObjectEvent);
  75.  
  76. ?>
File Description
  • ED example
  • PHP Code
  • 14 Jan-2021
  • 1.83 Kb
You can Share it: