DEV Community

Cover image for Singleton Theory - PHP
Fehmi Velioglu
Fehmi Velioglu

Posted on

1

Singleton Theory - PHP

Singleton design pattern, uygulamanın çalışma anında yalnızca 1 nesne(instance) yaratılmasını sağlamasıdır. 
Uygulamada aynı objeyi birçok kez kullanmak gerekiyor ise her seferinde tekrar tekrar instance oluşturmasını engelleyebiliriz. Bunu singleton design pattern ile static kullanarak sağlayabiliriz.

Eğer nesne daha önceden oluşturulmuş ise o nesne üzerinden, eğer oluşturulmamış ise yeni bir nesne oluşturarak yaşamına devam eder.

In memory, RAM üzerinden çalışır.

Private constructor yapılması önerilir.

class DbController
{
    private static $instance;
    public static $db;

    private function __construct()
    {
        $this->db = new PDO("mysql:host=localhost;dbname=***;", "root", "");
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new DbController;
        }
        return self::$instance;
    }

    public function dbConnection()
    {
        if (!isset(self::$db)) {
            self::$db = new PDO("mysql:host=localhost;dbname=***;", "root", "");
        }
        return self::$db;
    }
}
Enter fullscreen mode Exit fullscreen mode
$cont1 = DbController::getInstance();
$cont2 = DbController::getInstance();
var_dump($cont1);
var_dump($cont2);
if ($cont1 === $cont2) echo 'Same';
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more