diff --git a/function.php b/function.php index 6c6647d9..a310f418 100644 --- a/function.php +++ b/function.php @@ -5,6 +5,7 @@ defined('APP_PATH') or define('APP_PATH', __DIR__ . '/../../'); use HttpServer\Http\Response; use Snowflake\Snowflake; use HttpServer\Http\Context; +use Snowflake\Core\ArrayAccess; if (!function_exists('make')) { @@ -282,3 +283,19 @@ if (!function_exists('sweep')) { } } + + +if (!function_exists('merge')) { + + + /** + * @param $param + * @param $param1 + * @return array + */ + function merge($param, $param1) + { + return ArrayAccess::merge($param, $param1); + } + +} diff --git a/system/Observer/Observer.php b/system/Observer/Observer.php new file mode 100644 index 00000000..f5eb358d --- /dev/null +++ b/system/Observer/Observer.php @@ -0,0 +1,18 @@ +subscribes[$name] = $callback; + $this->params[$name] = $params; + return $this; + } + + + /** + * @param $params + * @param null $name + * @return mixed|void + * @throws Exception + */ + public function publish($name = null, $params = []) + { + if (empty($name)) { + return $this->release_all($params); + } + if (!isset($this->subscribes[$name])) { + throw new Exception('Subscribe ' . $name . ' not found.'); + } + $merge = $this->merge($name, $params); + return $this->subscribes[$name](new Dtl($merge)); + } + + + /** + * @param $params + */ + private function release_all($params) + { + foreach ($this->subscribes as $name => $subscribe) { + $merge = $this->merge($this->params[$name] ?? [], $params); + $subscribe(new Dtl($merge)); + } + } + + + /** + * @param $name + * @param $params + * @return mixed + */ + private function merge($name, $params) + { + if (!isset($this->params[$name])) { + return $params; + } + return merge($this->params[$name], $params); + } + + +}