PHP Data Objetcs (PDO) example



我对 php 中的面向对象编程相当陌生,我刚刚编写了以下脚本来使用 PDO 创建连接并运行简单的 Select Query。它工作正常,我只需要知道我是否做对了!(需要知道我缺少的最佳实践)。

<?php
class Connection
{
    protected $host = "localhost";
    protected $username = "admin";
    protected $password = "admin";  
    protected $database = "thedatabase";
    protected $dsn;
    protected $dbh;
    protected $opt = array(PDO::ATTR_ERRMODE=> PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE=> PDO::FETCH_ASSOC);
    protected $error_found = false;
    protected $error_message;
    function __construct()
    {
        $this->dsn = "mysql:host=$this->host;dbname=$this->database;charset=utf8";
        try
        {
            $this->dbh = new PDO($this->dsn, $this->username, $this->password, $this->opt);
        }
        catch (PDOException $e)
        {
            $this->error_message = $e->getMessage();
            $this->error_found = true;
        }
    }
    public function closeConnection()
    {
        $this->dbh = null;
    }
    public function errorsFound()
    {
        if ($this->error_found == true) 
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public function showError()
    {
        return $this->error_message;
    }
}
class Model extends connection
{
    public function select()
    {
        $sth = $this->dbh->query("SELECT * FROM `users`");
        $sth->setFetchMode(PDO::FETCH_ASSOC);
        while($row = $sth->fetch())
        {
            echo $row['username']."rn";
            echo $row['password']."rn";           
        }
    }
}
$connection = new Connection;
if ($connection->errorsFound()==true) 
{
    $error_messages = "Error: ".$connection->showError();
    echo $error_messages;
    $connection->closeConnection(); 
}
else
{
    $model = new Model;
    $model->select();
    $connection->closeConnection();
}
?>

对于基本实现来说,它看起来不错,除此之外,你不应该在类中回显某些东西。

如果你想看到一个实施良好的解决方案,看看泰勒·奥特威尔(taylor otwell)创建的雄辩。这应该会给你很多关于如何改进代码的想法。

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Connection.php

最新更新