How to use PDO connection in other classes?

后端 未结 1 553
慢半拍i
慢半拍i 2020-11-22 09:23

I think I\'ve a problem in understanding how OOP works. I already changed the code that it works, but it isn\'t the propper way I think. Following scenario (No, I\'m not cre

相关标签:
1条回答
  • 2020-11-22 10:13
    • your current class is rather useless. It would make sense to create a database wrapper if it adds some extra functionality to PDO. But given its current code, better to use vanilla PDO instead.
    • Either way, create a single $db instance from either vanilla PDO or your database class.
    • pass it as a constructor parameter into every class that needs a database connection

    database.php:

    <?php
    $host = '127.0.0.1';
    $db   = 'test';
    $user = 'root';
    $pass = '';
    $charset = 'utf8';
    
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $opt = [
        \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        \PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $pdo = new \PDO($dsn, $user, $pass, $opt);
    

    user.php

    <?php
    class User {
        /* Properties */
        private $conn;
    
        /* Get database access */
        public function __construct(\PDO $pdo) {
            $this->conn = $pdo;
        }
    
        /* List all users */
        public function getUsers() {
            return $this->conn->query("SELECT username, usermail FROM user")->fetchAll();
        }
    }
    

    app.php

    include 'database.php';
    $user = new User($pdo);
    $list = $user->getUsers();
    
    foreach($list as $test) {
        echo $test["username"],"\n";
    }
    

    output:

    username_foo
    username_bar
    username_baz
    

    Check out my (The only proper) PDO tutorial for more PDO details.

    0 讨论(0)
提交回复
热议问题