diff --git a/src/Artful.php b/src/Artful.php index cf9ba48..1de9d9a 100644 --- a/src/Artful.php +++ b/src/Artful.php @@ -6,6 +6,7 @@ use Closure; use Illuminate\Container\Container as LaravelContainer; +use think\Container as ThinkPHPContainer; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use Psr\Http\Message\MessageInterface; @@ -105,6 +106,15 @@ public static function set(string $name, mixed $value): void return; } + if ($container instanceof ThinkPHPContainer) { + $container->delete($name); + $container->bind($name, $value instanceof Closure ? $value : function () use ($value) { + return $value; + }); + + return; + } + if (method_exists($container, 'set')) { $container->set(...func_get_args()); @@ -150,7 +160,13 @@ public static function make(string $service, array $parameters = []): mixed public static function get(string $service): mixed { try { - return Artful::getContainer()->get($service); + $container = Artful::getContainer(); + + if ($container instanceof ThinkPHPContainer) { + return $container->make($service); + } else { + return $container->get($service); + } } catch (NotFoundExceptionInterface $e) { throw new ServiceNotFoundException('服务未找到: '.$e->getMessage()); } catch (ContainerNotFoundException $e) { diff --git a/src/Service/ContainerServiceProvider.php b/src/Service/ContainerServiceProvider.php index 5083298..7230372 100644 --- a/src/Service/ContainerServiceProvider.php +++ b/src/Service/ContainerServiceProvider.php @@ -8,6 +8,7 @@ use Hyperf\Context\ApplicationContext as HyperfContainer; use Hyperf\Pimple\ContainerFactory as DefaultContainer; use Illuminate\Container\Container as LaravelContainer; +use think\Container as ThinkPHPApplication; use Psr\Container\ContainerInterface; use Yansongda\Artful\Artful; use Yansongda\Artful\Contract\ServiceProviderInterface; @@ -23,6 +24,7 @@ class ContainerServiceProvider implements ServiceProviderInterface private array $detectApplication = [ 'laravel' => LaravelContainer::class, 'hyperf' => HyperfContainer::class, + 'thinkphp' => ThinkPHPApplication::class, ]; /** @@ -89,6 +91,23 @@ protected function hyperfApplication(): bool return true; } + /** + * @throws ContainerException + * @throws ContainerNotFoundException + */ + protected function thinkphpApplication() + { + Artful::setContainer(static fn() => ThinkPHPApplication::getInstance()); + + Artful::set(\Yansongda\Artful\Contract\ContainerInterface::class, ThinkPHPApplication::getInstance()); + + if (!Artful::has(ContainerInterface::class)) { + Artful::set(ContainerInterface::class, ThinkPHPApplication::getInstance()); + } + + return true; + } + /** * @throws ContainerException * @throws ContainerNotFoundException