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

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay