ClassLoader.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Di;
  12. use Dotenv\Dotenv;
  13. use Dotenv\Repository\Adapter;
  14. use Dotenv\Repository\RepositoryBuilder;
  15. use Hyperf\Di\Annotation\ScanConfig;
  16. use Hyperf\Di\Annotation\Scanner;
  17. use Hyperf\Di\LazyLoader\LazyLoader;
  18. use Hyperf\Di\ScanHandler\PcntlScanHandler;
  19. use Hyperf\Di\ScanHandler\ScanHandlerInterface;
  20. use Hyperf\Support\Composer;
  21. use Hyperf\Support\DotenvManager;
  22. class ClassLoader
  23. {
  24. public static function init(?string $proxyFileDirPath = null, ?string $configDir = null, ?ScanHandlerInterface $handler = null): void
  25. {
  26. if (! $proxyFileDirPath) {
  27. // This dir is the default proxy file dir path of Hyperf
  28. $proxyFileDirPath = BASE_PATH . '/runtime/container/proxy/';
  29. }
  30. if (! $configDir) {
  31. // This dir is the default config file dir path of Hyperf
  32. $configDir = BASE_PATH . '/config/';
  33. }
  34. if (! $handler) {
  35. $handler = new PcntlScanHandler();
  36. }
  37. $composerLoader = Composer::getLoader();
  38. if (file_exists(BASE_PATH . '/.env')) {
  39. DotenvManager::load([BASE_PATH]);
  40. }
  41. // Scan by ScanConfig to generate the reflection class map
  42. $config = ScanConfig::instance($configDir);
  43. $composerLoader->addClassMap($config->getClassMap());
  44. $scanner = new Scanner($config, $handler);
  45. $composerLoader->addClassMap(
  46. $scanner->scan($composerLoader->getClassMap(), $proxyFileDirPath)
  47. );
  48. // Initialize Lazy Loader. This will prepend LazyLoader to the top of autoload queue.
  49. LazyLoader::bootstrap($configDir);
  50. }
  51. /**
  52. * @see DotenvManager::load()
  53. * @deprecated use DotenvManager instead
  54. */
  55. protected static function loadDotenv(): void
  56. {
  57. $repository = RepositoryBuilder::createWithNoAdapters()
  58. ->addAdapter(Adapter\PutenvAdapter::class)
  59. ->immutable()
  60. ->make();
  61. Dotenv::create($repository, [BASE_PATH])->load();
  62. }
  63. }