HasRepository.php 895 B

1234567891011121314151617181920212223242526272829303132333435
  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\DbConnection\Traits;
  12. use Hyperf\Database\Model\Model;
  13. use RuntimeException;
  14. trait HasRepository
  15. {
  16. /**
  17. * @var string the full namespace of repository class
  18. */
  19. protected $repository;
  20. /**
  21. * @throws RuntimeException when the model does not define the repository class
  22. */
  23. public function getRepository()
  24. {
  25. if (! $this->repository || ! class_exists($this->repository) && ! interface_exists($this->repository)) {
  26. throw new RuntimeException(sprintf('Cannot detect the repository of %s', static::class));
  27. }
  28. return $this->getContainer()->get($this->repository);
  29. }
  30. }