PHP: Is a database level implementation acceptable? Code inside

I know singletons are bad. But is it bad for this?

class DaoMySQL {

    private static $instance;
    private $PDO;

    private function __construct() {
        $this->PDO = new PDO('mysql:dbname='.MYSQL_DEFAULT_DATABASE.';host='.MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD);
        $this->PDO->query('SET NAMES \'utf8\'');
    }

    /**
     * @return DaoMySQL
     */
    static public function singleton() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c();
        }
        return self::$instance;
    }

    /**
     * @return PDO
     */
    public function getPDO() {
        return $this->PDO;
    }

}

To use this, I am doing something like this. (This is from my Bean class, which applies to all data objects.)

public function delete() {
    $calledClassName = get_called_class();
    $query = "DELETE FROM `" . $calledClassName::table . "` WHERE `id` = $this->id";
    return DaoMySQL::singleton()->getPDO()->exec($query);
}
+3
source share
2 answers

Many people start using Dependency Injection containers to manage their objects, rather than using singletones. Perhaps worth a look? Then you need to make sure that the objects can access the container. You can get everything else from there.

Personally, I use sfServiceContainer from Symfony Components. This is a standalone DI container and seems pretty popular these days.

Update

. Fabien Potencier DI . ? , NIH.

, DI, sfServiceContainer. , sfServiceContainer - . Symfony - . , , PHP.

+2

(, ), Singletons, , .

+2

Source: https://habr.com/ru/post/1792944/


All Articles