[英]pdo connection position in php class
I'm using PDO now and I have a number of classes. 我现在正在使用PDO,并且有很多类。 Every time I use a class, I don't always use its database-related functions. 每次使用类时,我并不总是使用与数据库相关的功能。 Sometimes I keep using a class until at the end I might do some work with the database, like save this object to DB. 有时,我会一直使用类,直到最后我可以对数据库做一些工作,例如将对象保存到数据库。
So I'm currently doing something like this: 所以我目前正在做这样的事情:
class Something
{
protected $pdo;
function connect()
{
$this->pdo = new PDO( "mysql:host=".zConfig::read('hostname').";dbname=".zConfig::read('database'), zConfig::read('username'), zConfig::read('password'));
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
/* lots of functions doing lots of non-DB things */
function saveToDB()
{ $this->connect();
$this->pdo->prepare("Some SQL that saves some stuff");
// now do some DB-related pdo work
}
}
My question is - is this reasonable? 我的问题是-这合理吗? Is this the way a lot of you code? 这是你们许多人编码的方式吗?
As I see it, there are 3 options: 如我所见,有3个选项:
On the other hand, I could use a singleton database class like this: 另一方面,我可以使用像这样的单例数据库类:
I do have up to three related objects on a page, and sometimes I do and sometimes I don't need to connect to the DB more than once on a page. 我在一个页面上最多有三个相关的对象,有时候我确实需要,有时我不需要在页面上多次连接到数据库。 which design is safer? 哪种设计更安全?
You can just use lazy way. 您可以只使用惰性方式。
protected $pdo;
function connect()
{
if ($this->pdo === null)
{
$this->pdo = new PDO( "mysql:host=".zConfig::read('hostname').";dbname=".zConfig::read('database'), zConfig::read('username'), zConfig::read('password'));
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
Check this question . 检查这个问题 。
You should use DI, in your class to instantiate a connection, when your object is defined ex: 当您的对象定义为ex时,应在类中使用DI实例化连接:
class foo{
public $conn;
function __construct($conn){
$this->conn = $conn;
}
function doSomething(){
}
}
Now, if you find yourself, not wanting to instanciate a connection, whenever you are on a page/work that does not need database connection, and significantly slows your page, while trying to connect, use the PDO attribute 现在,如果您发现自己不想实例化连接,那么当您在不需要数据库连接的页面/工作中并且在尝试连接时显着降低页面速度时,请使用PDO属性
ATT_PERSISTENT
property like: ATT_PERSISTENT
属性,例如:
$conn = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx',
array( PDO::ATTR_PERSISTENT => true )
);
$object = new foo($conn);
Simply, once, you open a page, and connection is establish the ATTR_PERSISTENT
method will store that connection, pretty much like sessions work, and will keep feeding your page, and helping you from creating a new connection to your db, every time you refresh a page, or go on to another page. 只需简单地,一旦打开一个页面,便建立了连接, ATTR_PERSISTENT
方法将存储该连接,就像会话工作一样,并且将不断ATTR_PERSISTENT
页面,并在每次刷新时帮助您建立与数据库的新连接一个页面,或转到另一个页面。 Try, it.. and you'll see how faster your pages will load. 尝试一下..,您会看到页面加载的速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.