开发者

How should I pass a MySQL database link to a class in PHP?

I'm trying to make a small CMS for fun but I'm getting caught up on some semantics with OOP. I have a basic database class and then I have an administrator class. The admin class has to make database queries, so what I've been doing is having the admin class extend the db class and then passing the link to the db resource via construct. My code looks something like this:

class admin extends mysql {
    function __construct($link) {
        $this->link = $link; //$this->link is in the mysql class
    }
}
$db = new mysql($host,$user,$pass,$name);
$admin = new admin($db->link);

I know there should be an easier method to this without extending the db class (which I assume calls an entirely new instance of it). A friend told me to just pass the $db object to the admin class and store it there like so:

class admin {
    var $db;
    function __construct($db) {
    开发者_如何学编程    $this->db = $db;
    }
}

$db = new mysql($host,$user,$pass,$name);
$admin = new admin($db);

Is this the correct way to do things? Is there an easier way to reference the db link if it's already been established?


Yes, your friend is absolutely correct. Well, he's more correct than your original approach.

What you should do is go a step further and create a class whose only job is to query or update to the database and return results. That class is responsible for organizing queries (which are all prepared statements); your "admin" class knows nothing about how to connect to or query the database, only how to use this class, which we'll call "data_layer".

Pass an instance of the data_layer class to the admin class in the constructor, et voilà! You have made a layered program. Congratulations! You're taking your first steps toward a larger world.


I'd be inclined to declare and create an instance of the database class inside the admin class. The reason is that operations performed on the database by your admin class may not mix too well with other database access; the admin class might start or commit transactions at moments that are inconvenient for the rest of the application, for instance. That won't happen if the admin class has its own connection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜