Как обратиться к бд из статического класса в symfony?

Пользователь

от jaylen.trantow , в категории: PHP , год назад

Как обратиться к бд из статического класса в symfony?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

2 ответа

Пользователь

от margaret , год назад

@jaylen.trantow 

В Symfony, для доступа к базе данных из статического класса можно использовать EntityManager или Doctrine.


Пример использования EntityManager:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use DoctrineORMEntityManagerInterface;

class SomeClass
{
    private static $entityManager;

    public static function setEntityManager(EntityManagerInterface $entityManager)
    {
        self::$entityManager = $entityManager;
    }

    public static function doSomething()
    {
        $repository = self::$entityManager->getRepository(Entity::class);
        // ...
    }
}


Пример использования Doctrine:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use DoctrineBundleDoctrineBundleRegistry;

class SomeClass
{
    private static $doctrine;

    public static function setDoctrine(Registry $doctrine)
    {
        self::$doctrine = $doctrine;
    }

    public static function doSomething()
    {
        $entityManager = self::$doctrine->getManager();
        $repository = $entityManager->getRepository(Entity::class);
        // ...
    }
}


Обратите внимание, что статические методы в этом примере зависят от внешнего кода для установки EntityManager или Doctrine.

Пользователь

от rodger.botsford , год назад

@jaylen.trantow 

Для доступа к базе данных из статического класса в Symfony, вы можете использовать механизм внедрения зависимостей.

  1. Создайте сервис, который будет управлять вашими данными в базе данных.
  2. Внедрите зависимость EntityManager в сервис:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use DoctrineORMEntityManagerInterface;

class YourService
{
    private static $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        self::$entityManager = $entityManager;
    }

    public static function doSomething()
    {
        $repository = self::$entityManager->getRepository(YourEntity::class);
        // ...
    }
}


  1. Зарегистрируйте сервис в файле services.yaml:
1
2
3
4
services:
    AppServiceYourService:
        arguments:
            $entityManager: '@doctrine.orm.entity_manager'


Теперь вы можете использовать сервис YourService в статическом классе и иметь доступ к EntityManager.