Created
September 4, 2016 11:23
-
-
Save yanzadmiral/ea3bf3a3ab7ef1ac3ab72789d23ab0d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Observer { | |
| /** | |
| * Untuk singleton diperlukan satu property yang static | |
| * | |
| * @var array | |
| * @access protected | |
| */ | |
| protected static $listeners; | |
| /** | |
| * Membuat instance baru | |
| * | |
| * @return object | |
| * @access public | |
| * @constructor | |
| */ | |
| public function __construct() { | |
| if (self::$listeners === null) { | |
| // Dalam kasus agan ini adalah object mysqli | |
| self::$listeners = []; | |
| } | |
| } | |
| /** | |
| * Menambahkan closure ke stack | |
| * | |
| * @param Closure $callback | |
| * @return self | |
| * @access public | |
| */ | |
| public function attach($callback) { | |
| // Karena property static, maka harus menggunakan self bukan $this | |
| // Dan jangan lupa simbol $ juga ikut ditulis | |
| self::$listeners[] = $callback; | |
| return $this; | |
| } | |
| /** | |
| * Memanggil setiap fungsi dan menghapusnya dari stack | |
| * | |
| * @return self | |
| * @access public | |
| */ | |
| public function dispatch() { | |
| foreach (self::$listeners as $index => $callback) { | |
| $callback(); | |
| } | |
| // Reset listener | |
| self::$listeners = []; | |
| return $this; | |
| } | |
| /** | |
| * Megic method | |
| * | |
| * @param string $key | |
| * @return int|bool | |
| * @access public | |
| */ | |
| public function __get($key) { | |
| if ($key !== 'length') { | |
| echo "Undefine property ${key}"; | |
| return false; | |
| } | |
| return count(self::$listeners); | |
| } | |
| } | |
| // ---------------------------------------------------------- | |
| // Instance #1 | |
| // Menambah satu callback | |
| $foo = new Observer(); | |
| $foo->attach(function () { | |
| echo '<div>Instance #1</div>'; | |
| }); | |
| // Instance #2 | |
| // Menambah dua callback | |
| $bar = new Observer(); | |
| $bar->attach(function () { | |
| echo '<div>Instance #2'; | |
| })->attach(function () { | |
| echo '<div>Another Instance #2</div>'; | |
| }); | |
| // Instance #3 | |
| // Hanya membuat instance-nya saja | |
| $baz = new Observer(); | |
| $cek_1 = $foo->length === 3 && | |
| $bar->length === 3 && | |
| $baz->length === 3; | |
| // foo, bar atau baz tidak masalah | |
| $bar->dispatch(); | |
| $cek_2 = $foo->length === 0 && | |
| $bar->length === 0 && | |
| $baz->length === 0; | |
| var_dump($cek_1, $cek_2); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment