PDO代理是一个简单的事件驱动的PDO包装器,允许拦截和更改所有PDO方法的执行。
此类功能可用于:
PDOProxyPDO和PDOProxyPDOStatement类扩展了本机PDO和PDOStatement类,因此它们与任何预期常规PDO对象的方法兼容。
安装此库后,您必须提供代理配置,例如:
<?php
use PDOProxy EventManager ;
use PDOProxy ProxyConfiguration ;
use PDOProxy PDOCommand ;
$ ev = new EventManager ();
// you can alter the output of any method, like "__construct", "query", "prepare"...
// in order to do so, you must pass method name as an event name
// please note: multiple event listeners may be attached to a single event type
$ ev -> addEventListener ( " query " , function ( PDOCommand $ command , string $ eventName ) {
// you can alter the result of any PDO method
$ event -> setResult ( new PDOMockStatement ( " query " , " SELECT 1 " );
$ command -> stopPropagation ();
});
// you can intercept any method, like "__construct", "query", "prepare"...
// to do so, you must add "#pre" suffix to the event name
$ ev -> addEventListener ( " query#pre " , function ( PDOCommand $ command , string $ eventName ) {
// if you stop event propagation, the real PDO method won't be executed and the result will be taken from this callback
if ( $ command -> getArgs ()[ 0 ] == " SELECT 1 " ) {
$ command -> stopPropagation ();
}
});
ProxyConfiguration:: init ( $ ev );现在,您可以像常规PDO对象一样初始化pdoproxy:
<?php
use PDOProxy PDO ;
$ pdo = new PDO ( " dsn " , " user " , " password " , [ " option1 " => 1 , " option2 " => 2 ]);
$ result = $ pdo -> query ( " SELECT 2 " );
// [...]代理可以以两种不同的方式安装:
user@host:/directory$ composer require pdo-proxy/pdo-proxy
源代码可以在以下URL下的ZIP文件中找到:https://github.com/artur-graniszewski/pdo-proxy/archive/archive/master.zip
如上面的代码所示,每个事件处理程序都可以访问两个参数,特定Event对象和事件名称(如字符串)。
这是PDO代理提出的两种事件类型的概述:
它是在每次执行PDOProxyPDO类方法上提出的
<?php
namespace PDOProxy ;
interface PDOCommandInterface
{
public function getArgs () : array ;
public function setArgs ( array $ args );
public function getMethodName () : string ;
public function getResult ();
public function setResult ( $ result );
} getArgs()和setArgs()方法允许获取和更改输入参数传递给PDOProxyPDO方法,而getMethodName()允许检查执行哪个PDO方法。
getResult()和setResult()事件方法允许访问和更改结果,这些结果将通过特定的PDO方法返回。
它是在PDOProxyPDOStatement类方法的每一次执行中提出的
<?php
namespace PDOProxy ;
interface PDOStatementCommandInterface extends PDOCommandInterface
{
public function getParentArgs () : array ;
public function setParentArgs ( array $ args );
public function getParentMethodName () : string ;
} getParentArgs()和setParentArgs()方法允许传递给PDOProxyPDO方法,该方法创建了给定的PDOProxyPDOStatement对象,而getParentMethodName()允许在第一个位置中检查哪种PDO方法。
所有PDO事件都扩展了以下通用事件接口:
<?php
namespace PDOProxy ;
interface EventInterface
{
public function stopPropagation ();
public function isPropagationStopped () : bool ;
} stopPropagation()方法停止了进一步的事件传播(导致其他事件侦听器未针对给定的事件类型执行)。如果事件名称以“ #pre”句子的后缀(例如“ Query#pre”),则原始PDO/Pdostatement方法将不会在数据库上执行,在这种情况下,必须通过执行setResult()方法来模拟结果。
必须通过提供PDOProxyEventManager的实例为PDOProxyProxyConfiguration类的static init()方法来配置代理(请参见上文)。
请记住,在代理配置之前实例化PDOProxyPDO类会导致LogicException