还有另一种方法可以使此静态函数吗?

时间:2018-07-12 07:15:04

标签: php

如果由于内部规范而发生错误,我总是需要在对象中设置$error数组,但是我不知道这是否是这样做的最佳方法,因为checkIfExistsInTable()需要是静态函数。

final class Database {

    private $dbLink;

    public $hasError = false;

    public $error = [];

    public function __construct($driver, $host, $db, $username, $password, $encType = "utf8") {

        if ( in_array( strtolower($driver), PDO::getAvailableDrivers(), true) ) {

            // Create connection string !
            $dsn = "$driver:host=$host;dbname=$db";

            try {
                // New connection
                $this->dbLink = new PDO($dsn, $username, $password);

                // Set encType
                $this->dbLink->exec("SET NAMES $encType");

            } catch (PDOException $e) {

                $this->hasError = true;
                $this->error["code"] = 002;
                $this->error["message"] = $e->getMessage();

            }

        } else {

            $this->hasError = true;
            $this->error["code"] = 001;
            $this->error["message"] = "Couldn't find the database driver.";

        }
    }

    public static function checkIfExistsInTable(string $needle, string $haystack, string $table, Database $databaseObj):bool {

        $query = "SELECT COUNT(*) FROM $table WHERE $haystack=:value";

        try {

            $link = $databaseObj->getDbLink();

            $stmt = $link->prepare($query);
            $stmt->bindParam(":value", $needle);
            $stmt->execute();

            if ($stmt->fetchColumn() > 0) {

                return true;

            }

        } catch (PDOException $e) {

            $databaseObj->hasError = true;
            $databaseObj->error["code"] = 003;
            $databaseObj->error["message"] = "Error ocurred on " . __FUNCTION__ . ": " . $e->getMessage();

        }

        return false;
    }

    /**
     * Get PDO connection object
     *
     * @return  PDO
     */ 
    public function getDbLink()
    {
        return $this->dbLink;
    }

}

1 个答案:

答案 0 :(得分:1)

为了我的理智,这就是我要做的事情:

final class Database {

    private $dbLink;

    public $hasError = false;

    public $error = [];

    public function __construct($driver, $host, $db, $username, $password, $encType = "utf8") {

        if ( in_array( strtolower($driver), PDO::getAvailableDrivers(), true) ) {

            // Create connection string !
            $dsn = "$driver:host=$host;dbname=$db";

            try {
                // New connection
                $this->dbLink = new PDO($dsn, $username, $password);

                // Set encType
                $this->dbLink->exec("SET NAMES $encType");

            } catch (PDOException $e) {

                $this->hasError = true;
                $this->error["code"] = 002;
                $this->error["message"] = $e->getMessage();

            }

        } else {

            $this->hasError = true;
            $this->error["code"] = 001;
            $this->error["message"] = "Couldn't find the database driver.";

        }
    }

    public static function checkIfExistsInTable( string $needle, string $haystack, string $table, Database $databaseObj) {
         try { 
              $databaseObj->checkIfExists($needle, $haystack, $table);
         } catch (PDOException $e) {
              return false;
         }
    }

    public function checkIfExists(string $needle, string $haystack, string $table) :bool {

        // Good practice to escape field names in case someone sends "1=1 OR field" as a field name  
        $query = "SELECT COUNT(*) FROM $table WHERE `$haystack`=:value";

        try {

            $link = $this->getDbLink();

            $stmt = $link->prepare($query);
            $stmt->bindParam(":value", $needle);
            $stmt->execute();

            if ($stmt->fetchColumn() > 0) {

                return true;

            }

        } catch (PDOException $e) {

            $this->hasError = true;
            $this->error["code"] = 003;
            $this->error["message"] = "Error ocurred on " . __FUNCTION__ . ": " . $e->getMessage();
            throw $e; //Rethrow

        }

        return false;
    }

    /**
     * Get PDO connection object
     *
     * @return  PDO
     */ 
    public function getDbLink()
    {
        return $this->dbLink;
    }

}

这里有三个变化:

  1. 静态物体已移动到非静态物体。我认为这种方法更有意义
  2. 非静态更新错误并将其重新抛出。通常这很好,因为跟踪错误并不意味着您可以实际处理它,也许调用函数可以。
  3. 静态方法保留其退出行为,但现在仅是非静态方法的代理,并吞没了异常。这样,您可以使类以完全相同的方式工作,但将来可以大大简化重构。