开发者

Methods depends on field

Suppose I have this:

class Validator {
  private $db;

  public checkIfUsernameAlreadyExists开发者_运维百科($username) {
    if (!$this->db)
      return false;

  // Queries
  }
}

Assume the $db-object was created in the constructor (or a $db-object was given as a parameter in the constructor).

The problem is that all methods which have to use the $db-object need to check first if this object really exists. A database-connection may fail for several reasons. If it doesn't exist and no check was made, the script will crash ("method on non-object"-error).

Is there a way to work around this issue? Checking the object in every method doesn't sound the correct way. Or is it?

Thank you


Checking the object in every method is definitely not right.

The purpose of constructor arguments is to have a valid object to work with after it is instantiated:

class Validator {
  private $db;

  public function __construct(PDO $db) {
     // validate $db here
  }

  public checkIfUsernameAlreadyExists($username) {
     $this->db->query('SELECT * FROM table'); // exception thrown here
     // never reaches here
  }
}

try {
    $validator = new Validator(new PDO('mysql:dbname=db', 'user', 'pass'));
    $validator->checkIfUsernameAlreadyExists('foo');
} catch (PDOException $e) {
    echo 'Database error occured: ', $e->getMessage();
    exit(1);
}

So, you validate $db once in the constructor and that's it. If the database connection fails, then the $db object should (and will if it's PDO) throw an exception which will halt the execution of the method anyway.

Note: I'd discourage the use of Singleton pattern or global variables for a lot of reasons that can easily be found on Stack Overflow or Google.


The constructor of your class should handle this kind of check, e.g.:

class Validator {
    public function __construct($db) {
        if($db != null && $db->isConnected()) {
            $this->db = $db;
        }
        else
            throw Exception("Database error!");
    }
}

You could also use the Singleton pattern for the database object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜