开发者

How to run database class methods inside other classes?

I am new to using classes in PHP, I just realized, in most of my class methods, I need to do some mysql queries. I have another class that handles my connection and queries but how should I go about calling that class from other classes? Doesn't this k开发者_如何学运维ind of defeat the purpose of using classes if all my classes rely on my DB class?


this is usually solved with the Singleton or Factory pattern...

when you need to use the db, you snatch the app's db object:

$db = Site::getDb();   // singleton
$db->exec('update t set i = i + 1');

getDb returns a static instance.

or:

 $db = Db::getDb('dsn');   // factory
 $db->exec('update t set i = i + 1');

returns a static instance if it exists, or creates a new db handle for that dsn...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜