简体   繁体   English

如何将PHP文件中定义的PHP函数调用(参数,返回值)记录到数据库中?

[英]How to log PHP function calls (arguments, return value) defined in a PHP file to database?

I have read this previous question . 我已经阅读了上一个问题 My problem is similar: to debug some problems, I need to log all calls to functions in a source file includes/foo.php to database: 我的问题是相似的:要调试一些问题,我需要includes/foo.php文件includes/foo.php的源文件中所有函数的调用记录到数据库中:

<?php
function f1($arg1, $arg2) {
    return $arg1 . "x" . $arg2;
}
...
function f9($foo, $bar=array(), $baz=0) {
    return array(...);
}

What is the simplest way to do this? 最简单的方法是什么? I've thought of moving includes/foo.php to includes/foo.php_orig , renaming all functions in that source (eg f1 to f1__orig, and so on), then put in my own wrapper includes/foo.php : 我曾考虑过将includes/foo.php移到includes/foo.php_orig ,重命名该源中的所有函数(例如,将f1更改为f1__orig,依此类推),然后放入我自己的包装includes/foo.php

<?php
include "includes/logger.php";
include "includes/foo.php_orig";
function f1($arg1, $arg2) {
    $res = f1__orig($arg1, $arg2);
    log_fcall(array($arg1, $arg2), $res);
    return $res;
}
...
function f9($foo, $bar=array(), $baz=0) {
    $res = f9__orig($foo, $bar, $baz);
    log_fcall(array($foo, $bar, $baz), $res);
    return $res;
}

But this feels so tedious and manual. 但这感觉很繁琐和手动。 Does PHP offer another mechanism? PHP是否提供另一种机制? Or at least, some other constructs to ease the pains. 或至少,一些其他的构造可以减轻痛苦。

One way you could do this is using some wrapper magic and eval. 可以执行此操作的一种方法是使用一些包装魔术和评估。 This is not to say you should do it, since if this is for debugging, there are much better tools, eg debug_baktrace mentioned by 04FS in the comment. 这并不是说您应该这样做,因为如果这是为了调试,那么会有更好的工具,例如debug_baktracedebug_baktrace提到的debug_baktrace。 Additionally, eval may be disabled for you, depending on where you host your PHP code. 此外,根据您在何处托管PHP代码,可能会为您禁用eval

The wrapper would take the intended function name, and an anonymous function, like so: 包装器将使用预期的函数名称和一个匿名函数,如下所示:

$wrapped = array();

function logWrap($name, $func) {
  global $wrapped;
  $wrappedIndex = count($wrapped);
  $wrapped[] = $func;
  eval(
    "function ${name}() {"
    . "global \$wrapped;"
    . "\$args = func_get_args();"
    . "\$res = call_user_func_array(\$wrapped[${wrappedIndex}], \$args);"
    . "log_fcall(\$args, \$res);"
    . "return \$res;"
    . "}");
}

Then you can simply wrap your functions like so: 然后,您可以像这样简单地包装函数:

logWrap("f1", function($arg1, $arg2) {
    return $arg1 . "x" . $arg2;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM