Examples

1

Switching DB Drivers For Tests

<?php
use Patchwork\{redefine, getFunction, always};
$pdo = new PDO('sqlite:/tmp/demo.db');
redefine('pg_connect', always(null));
redefine('pg_query', function($query, ...$params) use ($pdo) {
 $stmt = $pdo->prepare($query);
 $stmt->execute($params);
 return $stmt;
});
redefine('pg_fetch_assoc', function(PDOStatement $stmt) {
 return $stmt->fetchAssoc();
});
# These will use SQLite instead:
pgsql_connect();
$result = pg_query('SELECT * FROM posts');
var_dump(pg_fetch_assoc($result));
<?php
# Patchwork has to be imported first, as it will not work on any script
# compiled earlier than itself. See Limitations.
# If using Composer, import /vendor/antecedent/patchwork/Patchwork.php.
require __DIR__ . '/patchwork.phar';
require __DIR__ . '/pgsql_to_sqlite.php';
# No more code here: this file is also compiled earlier than Patchwork,
# so moving the contents of pgsql_to_sqlite.php here would make this fail.
{
 "redefinable-internals": [
 "pg_connect",
 "pg_query",
 "pg_fetch_assoc"
 ]
}
Note that this would only work for queries that are compatible with both databases.
2

A Do-It-Yourself Profiler

<?php
use function Patchwork\{redefine, relay, getMethod};
$profiling = fopen('profiling.csv', 'w');
redefine('App\*', function(...$args) use ($profiling) {
 $begin = microtime(true);
 $result = relay();
 $end = microtime(true);
 fputcsv($profiling, [getMethod(), $end - $begin]);
 return $result;
});
<?php
# Patchwork has to be imported first, as it will not work on any script
# compiled earlier than itself. See Limitations.
# If using Composer, import /vendor/antecedent/patchwork/Patchwork.php.
require __DIR__ . '/patchwork.phar';
require __DIR__ . '/profiler.php';
# No more code here: this file is also compiled earlier than Patchwork,
# so moving the contents of profiler.php here would make this fail.

AltStyle によって変換されたページ (->オリジナル) /