它仅用于记录已访问的功能。而不是在每个函数中调用 log 函数。
如果不向方法中添加代码或使用单独的工具进行调试和分析,这是不容易实现的。
请注意,建议的解决方案__call
不适用于现有的公共方法,最终它会变得比仅添加log(__METHOD__)
到每个方法更复杂。
您正在寻找的基本上是面向方面的编程(AOP),它在 PHP 中并没有得到很好的支持。Flow3 框架使用注解和反射来动态添加方面。他们的日志记录示例完美地说明了您的用例:
namespace Example\MyPackage;
/**
* A logging aspect
*
* @Flow\Aspect
*/
class LoggingAspect {
/**
* @var \TYPO3\Flow\Log\LoggerInterface A logger implementation
*/
protected $logger;
/**
* For logging we need a logger, which we will get injected automatically by
* the Object Manager
*
* @param \TYPO3\Flow\Log\SystemLoggerInterface $logger The System Logger
* @return void
*/
public function injectSystemLogger(\TYPO3\Flow\Log\SystemLoggerInterface ⏎
$systemLogger) {
$this->logger = $systemLogger;
}
/**
* Before advice, logs all access to public methods of our package
*
* @param \TYPO3\Flow\AOP\JoinPointInterface $joinPoint: The current join point
* @return void
* @Flow\Before("method(public Example\MyPackage\.*->.*())")
*/
public function logMethodExecution(\TYPO3\Flow\AOP\JoinPointInterface $joinPoint) {
$logMessage = 'The method ' . $joinPoint->getMethodName() . ' in class ' .
$joinPoint->getClassName() . ' has been called.';
$this->logger->log($logMessage);
}
}
重要的一行是这样的:
@Flow\Before("method(public Example\MyPackage\.*->.*())")
它告诉框架在命名空间logMethodExecution
的任何类中的任何方法调用之前调用Example\MyPackage
。
因此,使用Flow3您可以做到。但是在没有 AOP 框架的情况下自己实现类似的行为必然会失败。