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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more