Я использую в классе соединения с бд, тк нет смысла наследовать этот класс. Подключение инициализируется и дальше работа идет в моделях
<?php
namespace app\Common\Mysql;
final class Connection
{
protected $link;
public function __construct() {
if ( is_null($this->link) ) {
try {
$attr = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
];
$this->link = new \PDO("mysql:host=localhost;dbname=dbname;charset=utf8", "user", "pass", $attr);
} catch (\PDOException $e) {
file_put_contents('log.txt', $e->getMessage(), FILE_APPEND);
}
}
}
/**
* @return \PDO;
*/
public function link() {
return $this->link;
}
}
update <?php
namespace app\Common\Model;
use app\Common\Mysql\Connection;
abstract class BaseModel {
private $connection;
/**
* prefix for tables
*/
const PREFIX = "";
/**
* @var
*/
protected $table;
/**
* @var
*/
protected $key;
public function __construct(Connection $conn) {
$this->connection = $conn->link();
}
public function findAll() {
return $this->fetch( "SELECT * FROM " . self::PREFIX . $this->table );
}
/**
* @param array $args
* @param $sql
* @return array|string
*/
public function findBy(Array $args, $sql) {
$stmt = $this->connection->prepare($sql);
$data = "";
if ( $stmt->execute($args) ) {
while ($row = $stmt->fetch()) {
$data[] = $row;
}
}
return $data;
}
/**
* @param $query
* @return mixed
*/
protected function fetch($query) {
$stmt = $this->connection->query($query);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$data = "";
while ( $row = $stmt->fetch() ) {
$data[] = $row;
}
return $data;
}
protected function save(Array $array, $sql) {
$sth = $this->connection->prepare($sql);
return $sth->execute($array);
}
protected function deleteById($id) {
$id = (int)$id;
return $this->connection->exec('DELETE FROM ' . self::PREFIX . $this->table . ' WHERE id = '.$id.'');
}
}