Создал первый класс для работы с БД
<?php
namespace Modules;
use PDO;
class MySqlDatabase
{
protected $_db;
public $last_query;
const DB_DSN = 'mysql:host=localhost;dbname=photo_gallery';
const DB_USER = "admin";
const DB_PASS = "123qwe";
//another methods
//Prepare statement SelectALL
public function prepareSelectAll($sql, $class)
{
try {
$stmt = $this->_db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_CLASS, $class);
return $data;
} catch (\PDOException $e) {
echo "Error prepareALL: " . $e->getMessage() . "<br/>";
echo $this->last_query = $sql;
}
}
//Prepare statement By ID
public function prepareSelectById($sql, $var1, $class)
{
try {
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":id", $var1, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchObject($class);
return $data;
} catch (\PDOException $e) {
echo "Error prepareById: " . $e->getMessage() . "<br/>";
echo $this->last_query = $sql;
}
}
}
Второй класс
<?php
namespace Modules;
class User
{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
//Select all
public static function findAll()
{
global $database;
$sql = "SELECT * FROM users";
$result_set = $database->prepareSelectAll($sql, __CLASS__);
return $result_set;
}
//Find by id
public static function findById($id = 0)
{
global $database;
$sql = "SELECT * FROM users WHERE id =:id LIMIT 1";
$resuls_set = $database->prepareSelectById($sql, $id, __CLASS__);
return $resuls_set;
}
}
И на стр вывода пока так:
require_once ('../vendor/autoload.php');
$database= new \Modules\MySqlDatabase();
$object= new \Modules\User();
$record=$object->findById(9);
И у меня вопрос правильно ли я делаю , используя global во втором классе. А если нет ,как лучше сделать?