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