Answer the question
In order to leave comments, you need to log in
Am I implementing the Active Record pattern correctly?
I took it for educational purposes to write a simple implementation of the Active Record pattern, I got such a service . Actually the question is simple - am I doing everything right?
So here's what I did.
Working with the database is encapsulated by the DB singleton class. It connects to the database:
private function __construct() {
$this->connect = new mysqli(self::HN, self::UN, self::PW, self::DB);
$this->connect->query('SET NAMES utf8');
mb_internal_encoding("UTF-8");
if ($this->connect->connect_error) {
die($conn->connect_error);
}
}
public static function getConnection() {
if (empty(static::$instance)) {
static::$instance = new static();
}
return static::$instance->connect;
}
public function update(array $data) {
$result = BookManager::update($this->id, $data);
$this->author = $result['author'];
$this->title = $result['title'];
$this->pages = $result['pages'];
$this->price = $result['price'];
}
private static $selectString = "SELECT * FROM books WHERE id = ?";
private static $multipleSelectString = "SELECT * FROM books ORDER BY id LIMIT ?, ?";
private static $updateString = "UPDATE books SET author = ?, title = ?, pages = ?, price = ? WHERE id = ?";
private static $insertString = "INSERT INTO books (author, title, pages, price) VALUES (?, ?, ?, ?)";
private static $countString = "SELECT COUNT(*) FROM books";
static public function getBook($id) {
$resultSet = static::getData($id);
return new Book(
$resultSet['id'],
$resultSet['author'],
$resultSet['title'],
$resultSet['pages'],
$resultSet['price']
);
}
static private function getData($id) {
global $db;
$stmt = $db->prepare(self::$selectString);
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
$resultSet = $result->fetch_assoc();
return $resultSet;
}
static public function getCount() {
global $db;
$stmt = $db->prepare(self::$countString);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
return $count;
}
static public function update($id, array $data) {
global $db;
$stmt = $db->prepare(self::$updateString);
$stmt->bind_param('ssiii',
$data['author'],
$data['title'],
$data['pages'],
$data['price'],
$id
);
$stmt->execute();
$resultSet = static::getData($id);
return $resultSet;
}
Answer the question
In order to leave comments, you need to log in
static is not OOP, global is not used for a long time. static
each instance of this class corresponds to one table entry;wiki/ActiveRecord
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question