A
A
Alexander2021-07-29 16:03:00
symfony
Alexander, 2021-07-29 16:03:00

How to use singleton?

Just started learning Symfony after Larael and Yii but can't figure out how to use singleton within Symfony.

In general, it is supposed to create a Setting class:

<?php

namespace App\Service;

class Setting
{
    private static $instance;

    private array $settings;

    protected function __construct() {}

    public function get($key)
    {
        if (empty($settings)) {
            $this->settings = // тут каким-то образом сделать запрос к базе
        }
        
        return $this->settings[$key] ?? null;
    }

    public static function getInstance(): self
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }
}


But I do not understand how I can make a request to the database. And then use this class both in controllers and in twig templates.

I decided to go through the services, there is no problem with the base, I have EntityManagerInterface in the constructor, but I don’t understand further. In the controller I also through DI, in the template through a global variable. But in the end, symfony makes a bunch of requests to the database, since apparently the service is not a singleton.

In which direction to dig? I've already broken my head.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question