📜 ⬆️ ⬇️

PDO: serialization, late initialization and PHPUnit

Hello. As you know, PDO does not support serialization . Several interesting things are connected with this, in particular surprises with traces and the inability to make a mock from PDO in PHPUnit .

I actively use PHPUnit and once again implementing the Dependency Injection pattern, I encountered the described difficulties of creating a Mock object from PDO.


')
This is what I wanted to achieve:
class MyTest
extends \PHPUnit_Framework_TestCase
{
...
protected function setUp()
{
$ this ->pdo = $ this ->getMock( 'PDO' );
$ this ->myObject = new MyClass($ this ->pdo);
}
}


* This source code was highlighted with Source Code Highlighter .


As a solution, the LazyPDO class, the successor of PDO, was written, which can be painless and (de) serialized, and it retains a set of connection attributes, regardless of whether they were passed to the constructor or to setAttribute (). The code is posted on github .

I will be glad to criticism.

Source: https://habr.com/ru/post/120661/


All Articles