简体   繁体   English

如何在其他类中运行数据库类方法?

[英]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. 我刚接触PHP中的类,我才意识到,在大多数类方法中,我需要执行一些mysql查询。 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 kind of defeat the purpose of using classes if all my classes rely on my DB class? 如果我所有的类都依赖于我的DB类,这是否会破坏使用类的目的?

this is usually solved with the Singleton or Factory pattern... 这通常可以通过Singleton或Factory模式解决...

when you need to use the db, you snatch the app's db object: 当需要使用数据库时,可以抢占应用程序的db对象:

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

getDb returns a static instance. getDb返回一个静态实例。

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... 返回一个静态实例(如果存在),或为该dsn创建一个新的数据库句柄...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM