From f8e2492f440ca3f2a8c5e6916433e91e9c05d4df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mr=C2=B7x?= Date: Wed, 2 Sep 2020 20:07:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.php | 17 +++++++ system/Observer/Observer.php | 18 ++++++++ system/Observer/Subscribe.php | 87 +++++++++++++++++++++++++++++++++++ 3 files changed, 122 insertions(+) create mode 100644 system/Observer/Observer.php create mode 100644 system/Observer/Subscribe.php 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); + } + + +}