M
M
Maxim Anarchistov2020-03-20 02:51:57
symfony
Maxim Anarchistov, 2020-03-20 02:51:57

How to access the database from a static class in symfony?

I have created a static class inside Symfony (no dependencies of Symfony itself) and I want to work with the database using Doctrine. Also I have table entity in DB and repository for this Entity.

As I understand it, I am missing the ContainerInterface, which is automatically in the controller generated by Symfony, but I do not have a controller.

The manuals tell me that there is such a way:

/** @var FramePagesRepository */
protected $framePages;

public function __construct(FramePagesRepository $framePages) {
    $this->framePages = $framePages;
}


But it already looks a little crutch and requires a dynamically created class, and I have a static one. In addition, as I understand, the injection will not work, even if I create this class dynamically, because I will do it through new. Is it possible to somehow completely decouple work from the database from the Symphony structure and access the Table Repository directly?

You can also create a Symfony Console script and take the EntityManager from there, dragging it through new to the places I need when creating classes, but this looks even more crutch.

Most likely, due to little experience, my approach is wrong in general, so I will describe the situation in full:

I have a symfony and websocket Ratchet server that works outside of the Cinfony structure, which communicates with the html page. The server is started by running a php script via cron.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Anarchistov, 2020-12-24
@ozonar

You can get a connection to the database through DBAL (an abstraction layer that runs on top of PDO).

$config = new \Doctrine\DBAL\Configuration();
$connectionParams = array(
    'dbname' => 'mydb',
    'user' => 'user',
    'password' => 'secret',
    'host' => 'localhost',
    'driver' => 'pdo_mysql',
);

$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);

$conn->createQueryBuilder()->select('*')
    ->from('users')
    ->where('id = :id')
    ->setParameter('id', 1);

Using abstractions of Symphony models and generally the advantages of the framework (like DI) in this case will not work.
There is no analogue in Symfony. The authors of Symfony are against such work with the database, since this way of interaction violates the principles of SOLID
User::find()->where(['email' => $email])->one();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question