This commit is contained in:
2020-09-02 20:07:02 +08:00
parent 046ce49386
commit f8e2492f44
3 changed files with 122 additions and 0 deletions
+17
View File
@@ -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);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Snowflake\Observer;
use Snowflake\Abstracts\Component;
/**
* Class Observer
* @package Snowflake\Observer
*/
class Observer extends Component
{
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace Snowflake\Observer;
use Exception;
use Snowflake\Abstracts\Component;
use Snowflake\Core\ArrayAccess;
use Snowflake\Core\Dtl;
/**
* Class Subscribe
* @package Snowflake\Observer
*/
class Subscribe extends Component
{
public $subscribes = [];
public $params = [];
/**
* @param $name
* @param $callback
* @param array $params
* @return Subscribe
* @throws Exception
*/
public function subscribe($name, $callback, array $params = [])
{
if (!is_callable($callback, true)) {
throw new Exception('Subscribe must need callback.');
}
$this->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);
}
}