diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index e5f51f5..6f9a5e5 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -9,6 +9,7 @@ use app\Event\TestEvent; use app\Facade\TestFacade; +use app\Listener\TestEventListener; use app\Middleware\TestMiddleware; use app\Model\UserModel; use app\Service\Entity\ExchGiftInfo; @@ -18,6 +19,7 @@ use app\Utils\LogBase; use Carbon\Carbon; use dcr\Annotation\Mapping\RequestMapping; +use dcr\EventInstance; use DI\Attribute\Inject; use Exception; use Gregwar\Captcha\CaptchaBuilder; @@ -26,6 +28,7 @@ use Inhere\Validate\Validation; use Intervention\Image\Facades\Image; use Intervention\Image\ImageManager; +use Symfony\Component\EventDispatcher\EventDispatcher; class TestController extends Controller { @@ -130,21 +133,17 @@ public function test4(): string /** * 测试事件 - * @see https://github.com/inhere/php-event-manager + * @see https://www.doctrine-project.org/projects/doctrine-event-manager/en/latest/reference/index.html#setup */ #[RequestMapping(methods: 'GET , POST', path:'/test/event')] public function event(): string { - $test = request()->get('aa', 23); - $test = $this->request->get('ab', 24); - echo $test; $params = [ 'test' => 23, ]; + event(new TestEvent($params),TestEvent::NAME); + // 初始化事件分发器 - // return reponse()->setContent('abc')->send(); - - event(TestEvent::preFoo, $params); return apiResponse([]); } diff --git a/app/Event/TestEvent.php b/app/Event/TestEvent.php index 1d90ced..a8d4769 100644 --- a/app/Event/TestEvent.php +++ b/app/Event/TestEvent.php @@ -1,52 +1,28 @@ addEventListener([self::preFoo, self::postFoo], $this); - } + protected $params; - public function preFoo(EventArgs $eventArgs): void + public function __construct($params) { - var_dump($eventArgs); - echo 111; - echo '
'; - $this->preFooInvoked = true; + $this->params = $params; } - public function postFoo(EventArgs $eventArgs): void + public function getParams() { - echo 222; - $this->postFooInvoked = true; + return $this->params; } -} +} \ No newline at end of file diff --git a/app/Listener/BaseListenerInterface.php b/app/Listener/BaseListenerInterface.php new file mode 100644 index 0000000..a38dc18 --- /dev/null +++ b/app/Listener/BaseListenerInterface.php @@ -0,0 +1,10 @@ +preFooInvoked = true; - } - - public function getSubscribedEvents(): array + public function process(object $event) { - return []; - // return [TestEvent::preFoo]; + echo '打印参数'.PHP_EOL; + var_dump($event->getParams()); } -} +} \ No newline at end of file diff --git a/app/Provider/EventServiceProvider.php b/app/Provider/EventServiceProvider.php index 151da9f..e93bc45 100644 --- a/app/Provider/EventServiceProvider.php +++ b/app/Provider/EventServiceProvider.php @@ -13,12 +13,12 @@ /** * 事件 - * @see https://www.doctrine-project.org/projects/doctrine-event-manager/en/latest/reference/index.html#setup + * @see https://code.tutsplus.com/tutorials/handling-events-in-your-php-applications-using-the-symfony-eventdispatcher-component--cms-31328 */ class EventServiceProvider { /** - * @return string[] + * @return array */ public static function getEventConfig() { diff --git a/app/helpers.php b/app/helpers.php index 4bd1e70..1eea76b 100644 --- a/app/helpers.php +++ b/app/helpers.php @@ -1,23 +1,24 @@ -getFile()), + // Logger::exception(basename($exception->getFile()), // $exception->getFile(), $exception->getLine(), -// $exception->getMessage(), $exception->getCode(), $exception->getTraceAsString(), array( -// "action" => $request->header("HOST") . $request->server("REQUEST_URI"), -// "server_ip" => gethostname(), -// )); + // $exception->getMessage(), $exception->getCode(), $exception->getTraceAsString(), array( + // "action" => $request->header("HOST") . $request->server("REQUEST_URI"), + // "server_ip" => gethostname(), + // )); $log_data = ''; $log_data .= date('Y-m-d H:i:s').' '.$exception->__toString(); @@ -78,13 +79,14 @@ function cException($exception): void return; } -if (! function_exists('str_random')) { + +if ( !function_exists('str_random')) { /** * Generate a more truly "random" alpha-numeric string. * * @param int $length - * @return string * + * @return string * @throws \RuntimeException */ function str_random($length = 16) @@ -95,7 +97,7 @@ function str_random($length = 16) function writeLog($msg, $name = null, $logDir = null) { - if (!$name) { + if ( !$name) { $name = date('Y-m-d_H', time()); } else { if ($logDir === null) { @@ -113,7 +115,7 @@ function writeLog($msg, $name = null, $logDir = null) $logDir = '/'.'pre_'.'/'.date('Ym', time()).'/'.date('d', time()); } - if (!file_exists(PROJECT_ROOT.'runtime/errlog/'.$logDir)) { + if ( !file_exists(PROJECT_ROOT.'runtime/errlog/'.$logDir)) { mkdir(PROJECT_ROOT.'runtime/errlog/'.$logDir, 0777, true); } @@ -240,7 +242,7 @@ function xmlToArray($xml) } -if (!function_exists('objToArray')) { +if ( !function_exists('objToArray')) { function objToArray($o) { // return json_decode( json_encode($o),1 ); @@ -330,7 +332,7 @@ function errorx($message = '失败', $code = 404, $data = '') } -if (!function_exists('cache')) { +if ( !function_exists('cache')) { function cache($key, Closure $closure, $ttl = null) { if ($result = \app\Utils\Redis::connection()->get($key)) { @@ -347,12 +349,13 @@ function getRedis() return \app\Utils\Redis::connection(); } + function apiLog($jsonArr): void { } -if (!function_exists('collectNew')) { +if ( !function_exists('collectNew')) { /** * @param null|array|Collection $value * @param bool $toLine @@ -375,7 +378,7 @@ function collectNew($value = null, $toLine = false) } } -if (!function_exists('socketSend')) { +if ( !function_exists('socketSend')) { function socketSend(int $uid, array $data): bool { $strData = Json::encode($data); @@ -393,7 +396,7 @@ function socketSend(int $uid, array $data): bool } } -if (!function_exists('retry')) { +if ( !function_exists('retry')) { /** * $data = retry(3, function () { * $rand = mt_rand(1, 10); @@ -432,12 +435,12 @@ function real_ip() { $ip = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all( - '#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', - $_SERVER['HTTP_X_FORWARDED_FOR'], - $matches - )) { + '#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', + $_SERVER['HTTP_X_FORWARDED_FOR'], + $matches + )) { foreach ($matches[0] as $xip) { - if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) { + if ( !preg_match('#^(10|172\.16|192\.168)\.#', $xip)) { $ip = $xip; break; } @@ -453,8 +456,6 @@ function real_ip() } - - function di($name = null): \DI\Container { if ($name == null) { @@ -464,17 +465,10 @@ function di($name = null): \DI\Container } -function event(string $eventName = '', array $eventArgs = []): bool +function event($event,string $eventName = ''): bool { - $eventManager = EventInstance::instance(); - - // EventServiceProvider 中配置 - // $testEvent = new TestEvent($eventManager); - // $eventManager->addEventSubscriber(new TestEventListener()); - - $eventArgsObj = EventArgs::getEmptyInstance(); - $eventArgsObj->params = $eventArgs; - $eventManager->dispatchEvent($eventName, $eventArgsObj); + $dispatcher = EventInstance::instance(); + $dispatcher->dispatch($event, $eventName); return true; } @@ -523,7 +517,7 @@ function stringToLine(string $string): string } -if (!function_exists('array_multi_column')) { +if ( !function_exists('array_multi_column')) { function array_multi_column(array $array, array $column): array { return array_map(function ($data) use ($column) { @@ -532,7 +526,7 @@ function array_multi_column(array $array, array $column): array } } -if (!function_exists('call')) { +if ( !function_exists('call')) { /** * Call a callback with the arguments. * @@ -630,16 +624,19 @@ function arrayToEntity(array $array, object $entity): object return $entity; } + function request(): SymfonyRequest { return SymfonyRequest::createFromGlobals(); } + function reponse(): SymfonyResponse { return \dcr\Response\Response::instance(); } + function config(string $str) { return Config::get($str); @@ -648,7 +645,7 @@ function config(string $str) function createDirectoryIfNeeded($directory): void { - if (!file_exists($directory) || !is_dir($directory)) { + if ( !file_exists($directory) || !is_dir($directory)) { mkdir($directory, 0777, true); } } diff --git a/dcr/Boostrap.php b/dcr/Boostrap.php index 7af7145..494ff64 100644 --- a/dcr/Boostrap.php +++ b/dcr/Boostrap.php @@ -8,12 +8,18 @@ namespace dcr; +use app\Event\TestEvent; +use app\Listener\TestEventListener; use app\Provider\EventServiceProvider; use app\Utils\Config; use dcr\Annotation\RouteAnnotation; +use DI\ContainerBuilder; use Dotenv\Dotenv; use Illuminate\Database\Capsule\Manager as Capsule; +use Symfony\Component\DependencyInjection\ContainerBuilder as SymfonyContainerBuilder; +use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass; +use Symfony\Component\EventDispatcher\EventDispatcher; /** * 初始化 注册 各种 env config orm 门面 事件 * 捕获异常,错误控制 @@ -100,12 +106,14 @@ protected function loadDotEnv(): void */ protected function loadEvents(): void { - $eventManager = EventInstance::instance(); - $configs = EventServiceProvider::getEventConfig(); - - foreach ($configs as $event => $listeners) { - new $event($eventManager); - $eventManager->addEventSubscriber(new $listeners()); + $dispatcher = EventInstance::instance(); + $configs = EventServiceProvider::getEventConfig(); + foreach($configs as $eventClass =>$listenerClass) + { + $listener = new $listenerClass(); + $dispatcher->addListener($eventClass::NAME, [$listener, 'process']); } +// $listener = new TestEventListener(); +// $dispatcher->addListener(TestEvent::NAME, [$listener, 'process']); } } diff --git a/dcr/EventInstance.php b/dcr/EventInstance.php index ca33021..24d1d5a 100644 --- a/dcr/EventInstance.php +++ b/dcr/EventInstance.php @@ -8,31 +8,28 @@ namespace dcr; -use Doctrine\Common\EventManager; use Exception; +use Symfony\Component\EventDispatcher\EventDispatcher; /** * 事件 - * @see https://www.doctrine-project.org/projects/doctrine-event-manager/en/latest/reference/index.html#setup + * @see https://code.tutsplus.com/tutorials/handling-events-in-your-php-applications-using-the-symfony-eventdispatcher-component--cms-31328 */ class EventInstance { - /** - * @var EventManager - */ - public static $ins; + public static $event; /** * @throws Exception */ public static function instance() { - if (!self::$ins) { - $ins = new EventManager; - self::$ins = $ins; - return self::$ins; + if (!self::$event) { + $ins = new EventDispatcher; + self::$event = $ins; + return self::$event; } - return self::$ins; + return self::$event; } }