I'm trying to use Dependency Injection and Factory class. I've read quite a bit about this and seen a lot of examples. But I don't think I'm using DI correctly (of Facotry class for that mater.
I'm not able to query my database. I get the error:
Fatal error: Call to undefined method Conn::query()
.
The problem is in the getRows($sql)
function.
It seems I've not been able to use DI correctly and it's not able to use PDO
functions.
Can someone point me in the right direction and maybe see what I'm doing wrong?
This is my code so far.
$user = Factory::createUser();
$result = $user->getUsers();
print_r($result);
And here are all the other classes:
class Factory {
// I think I'm using Dependency Injection here
function createUser($id = NULL) { return new User(new Conn(), $id); }
}
//Returns PDO conection and that's it.
class Conn {
function config($cfg_file = 'sl.config') {
/* The code here returns $conf array */
}
function Conn() {
$conf = $this->config();
try { return new PDO($conf['dsn'], $conf['user'], $conf['pass']); }
catch (PDOException $e) { echo $e->getMessage(); }
}
}
interface iUser {
public function getSomething();
}
// This is where I do all my SQL queries and return results.
class UserDAO {
private $db = NULL;
private $id;
function UserDAO (&$db, &$id = NULL) {
$this->db = &$db;
$this->id = &$id;;
}
public function getRows($sql)
{
$result = $this->db->query($sql); // <------- THIS IS NOT WORKING
$row = $result->fetch(PDO::FETCH_ASSOC);
return $row;
}
function getUsers($limit = 10) {
$sql ="SELECT * FROM users LIMIT $limit";
return $this->getRows($sql);
}
}
class User extends UserDAO implements iUser {
public function getSomething() {
echo "Something";
}
}