ClassLoader.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. class ClassLoader
  22. {
  23. public static function init(?string $proxyFileDirPath = null, ?string $configDir = null, ?ScanHandlerInterface $handler = null): void
  24. {
  25. if (! $proxyFileDirPath) {
  26. // This dir is the default proxy file dir path of Hyperf
  27. $proxyFileDirPath = BASE_PATH . '/runtime/container/proxy/';
  28. }
  29. if (! $configDir) {
  30. // This dir is the default proxy file dir path of Hyperf
  31. $configDir = BASE_PATH . '/config/';
  32. }
  33. if (! $handler) {
  34. $handler = new PcntlScanHandler();
  35. }
  36. $composerLoader = Composer::getLoader();
  37. if (file_exists(BASE_PATH . '/.env')) {
  38. static::loadDotenv();
  39. }
  40. // Scan by ScanConfig to generate the reflection class map
  41. $config = ScanConfig::instance($configDir);
  42. $composerLoader->addClassMap($config->getClassMap());
  43. $scanner = new Scanner($config, $handler);
  44. $composerLoader->addClassMap(
  45. $scanner->scan($composerLoader->getClassMap(), $proxyFileDirPath)
  46. );
  47. // Initialize Lazy Loader. This will prepend LazyLoader to the top of autoload queue.
  48. LazyLoader::bootstrap($configDir);
  49. }
  50. protected static function loadDotenv(): void
  51. {
  52. $repository = RepositoryBuilder::createWithNoAdapters()
  53. ->addAdapter(Adapter\PutenvAdapter::class)
  54. ->immutable()
  55. ->make();
  56. Dotenv::create($repository, [BASE_PATH])->load();
  57. }
  58. }