FactoryLocator.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.3.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Datasource;
  16. use Cake\ORM\TableRegistry;
  17. use InvalidArgumentException;
  18. /**
  19. * Class FactoryLocator
  20. */
  21. class FactoryLocator
  22. {
  23. /**
  24. * A list of model factory functions.
  25. *
  26. * @var callable[]
  27. */
  28. protected static $_modelFactories = [];
  29. /**
  30. * Register a callable to generate repositories of a given type.
  31. *
  32. * @param string $type The name of the repository type the factory function is for.
  33. * @param callable $factory The factory function used to create instances.
  34. * @return void
  35. */
  36. public static function add($type, callable $factory)
  37. {
  38. static::$_modelFactories[$type] = $factory;
  39. }
  40. /**
  41. * Drop a model factory.
  42. *
  43. * @param string $type The name of the repository type to drop the factory for.
  44. * @return void
  45. */
  46. public static function drop($type)
  47. {
  48. unset(static::$_modelFactories[$type]);
  49. }
  50. /**
  51. * Get the factory for the specified repository type.
  52. *
  53. * @param string $type The repository type to get the factory for.
  54. * @throws \InvalidArgumentException If the specified repository type has no factory.
  55. * @return callable The factory for the repository type.
  56. */
  57. public static function get($type)
  58. {
  59. if (!isset(static::$_modelFactories['Table'])) {
  60. static::$_modelFactories['Table'] = [TableRegistry::getTableLocator(), 'get'];
  61. }
  62. if (!isset(static::$_modelFactories[$type])) {
  63. throw new InvalidArgumentException(sprintf(
  64. 'Unknown repository type "%s". Make sure you register a type before trying to use it.',
  65. $type
  66. ));
  67. }
  68. return static::$_modelFactories[$type];
  69. }
  70. }