如何阻止PDO从建立连接直到第一个查询? [英] How to detain PDO from establishing a connection until the first query?

查看:81
本文介绍了如何阻止PDO从建立连接直到第一个查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次执行脚本时,我都在建立与数据库的连接.通过将PDO实例分配给全局$db变量,然后将其传递给控制器​​来完成.

$db = new \ay\pdo\PDO('mysql:dbname=foo;charset=utf8');

但是,由于存在高速缓存逻辑层,因此95%的请求不需要执行单个查询.虽然建立连接所需的5毫秒似乎并不重要,但它是请求时间的30%.如果一分钟要处理多达20万个请求,这是一个很大的数字.

仅在有要执行的查询时,我才想建立与数据库的连接.建议在不增加脚本开销的情况下实现此目标的方法是什么?

解决方案

您可以/可以使用代理设计模式.因此,当您第一次请求数据时,它将处理/创建与db的连接.

因此,直接使用PDO代替您创建代理对象,当存在查询时,它将创建与db的连接,并查询它(延迟加载),然后稍后将重用同一PDO对象.

http://en.wikipedia.org/wiki/Proxy_pattern

http://en.wikipedia.org/wiki/Flyweight_pattern

代理示例: https://github.com/ezimuel /PHP-design-patterns/blob/master/Proxy.php

I am establishing a connection to the database upon every script execution. It is done by assigning a PDO instance to a global $db variable that is then passed to the controller.

$db = new \ay\pdo\PDO('mysql:dbname=foo;charset=utf8');

However, because there is a cache-logic layer, 95% requests do not need to execute a single query. While 5ms to establish a connection might not seem significant, it is 30% of the request time. When serving up to 200K requests a minute, this is a significant number.

I would like to establish a connection to the database only when there is a query to execute. What is the recommended way of achieving this without putting a significant overhead on the script?

解决方案

You may/can use proxy design pattern. So it will handle/create connection to db when you first time ask for data.

So instead using PDO directly you create proxy object, when there is query it creates connection to db, and query it (lazy loading), then later on it would reuse the same PDO object.

http://en.wikipedia.org/wiki/Proxy_pattern

http://en.wikipedia.org/wiki/Flyweight_pattern

Proxy example: https://github.com/ezimuel/PHP-design-patterns/blob/master/Proxy.php

这篇关于如何阻止PDO从建立连接直到第一个查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆