From 843bdb73fec1be0347e98b1add3b04a0913031c0 Mon Sep 17 00:00:00 2001 From: Edward Yang Date: Wed, 1 Feb 2023 12:03:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=8F=92=E4=BB=B6middleware?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Shop/Providers/PluginServiceProvider.php | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/beike/Shop/Providers/PluginServiceProvider.php b/beike/Shop/Providers/PluginServiceProvider.php index f76594ea..13a6d3d5 100644 --- a/beike/Shop/Providers/PluginServiceProvider.php +++ b/beike/Shop/Providers/PluginServiceProvider.php @@ -55,6 +55,7 @@ class PluginServiceProvider extends ServiceProvider $this->loadRoutes($pluginCode); $this->loadViews($pluginCode); $this->loadTranslations($pluginCode); + $this->registerMiddleware($pluginCode); } } @@ -136,4 +137,55 @@ class PluginServiceProvider extends ServiceProvider $pluginBasePath = $this->pluginBasePath; $this->loadViewsFrom("{$pluginBasePath}/{$pluginCode}/Views", $pluginCode); } + + /** + * 注册插件定义的中间件 + */ + private function registerMiddleware($pluginCode) + { + $pluginBasePath = $this->pluginBasePath; + $middlewarePath = "{$pluginBasePath}/{$pluginCode}/Middleware"; + + $router = $this->app['router']; + $shopMiddlewares = $this->loadMiddlewares("$middlewarePath/Shop"); + $adminMiddlewares = $this->loadMiddlewares("$middlewarePath/Admin"); + + if ($shopMiddlewares) { + foreach ($shopMiddlewares as $shopMiddleware) { + $router->pushMiddlewareToGroup('shop', $shopMiddleware); + } + } + + if ($adminMiddlewares) { + foreach ($adminMiddlewares as $adminMiddleware) { + $router->pushMiddlewareToGroup('admin', $adminMiddleware); + } + } + } + + /** + * 获取插件中间件 + * @param $path + * @return array + */ + private function loadMiddlewares($path): array + { + if (! file_exists($path)) { + return []; + } + + $middlewares = []; + $files = glob("$path/*"); + foreach ($files as $file) { + $baseName = basename($file, '.php'); + $namespacePath = 'Plugin' . dirname(str_replace($this->pluginBasePath, '', $file)) . '/'; + $className = str_replace('/', '\\', $namespacePath . $baseName); + + if (class_exists($className)) { + $middlewares[] = $className; + } + } + + return $middlewares; + } }