Need help with Factory and Dependency Injection
I'm trying to use Dependency Injection and Factory class. I've read quite a bit about this and seen a lot of examples.开发者_StackOverflow社区 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";
}
}
You're trying to return an object in your Conn
constructor, which just doesn't happen. Constructors return void
. Add another method, like the getDatabaseObject
method I've added below to return your PDO
object.
class Conn {
function Conn() {
$conf = $this->config();
}
public function getDatabaseObject() {
try { return new PDO($conf['dsn'], $conf['user'], $conf['pass']); }
catch (PDOException $e) { echo $e->getMessage(); }
}
}
class Factory {
// I think I'm using Dependency Injection here
function createUser($id = NULL) {
$c = new Conn();
return new User($c->getDatabaseObject(), $id);
}
}
You're passing your User constructor a connection and an id
return new User(new Conn(), $id);
Since the User class doesnt have a constructor php fires the base class' constructor
function UserDAO (&$db, &$id = NULL) {
$this->db = &$db;
$this->id = &$id;;
}
So essentially you are passing the UserDAO a connection object when it wants a db object
That's why its trying to run the query
function on the Conn
object
精彩评论