Method interception in PHP 5.*
- by Rolf
Hi everybody,
I'm implementing a Log system for PHP, and I'm a bit stuck.
All the configuration is defined in an XML file, that declares every method to be logged. XML is well parsed and converted into a multidimensionnal array (classname = array of methods). So far, so good.
Let's take a simple example:
#A.php
class A {
public function foo($bar) {
echo ' // Hello there !';
}
public function bar($foo) {
echo " $ù$ùmezf$z !";
}
}
#B.php
class B {
public function far($boo) {
echo $boo;
}
}
Now, let's say I've this configuration file:
<interceptor>
<methods class="__CLASS_DIR__A.php">
<method name="foo">
<log-level>INFO</log-level>
<log-message>Transaction init</log-message>
</method>
</methods>
<methods class="__CLASS_DIR__B.php">
<method name="far">
<log-level>DEBUG</log-level>
<log-message>Useless</log-message>
</method>
</methods>
</interceptor>
The thing I'd like AT RUNTIME ONLY (once the XML parser has done his job) is:
#Logger.php (its definitely NOT a final version) -- generated by the XML parser
class Logger {
public function __call($name,$args) {
$log_level = args[0];
$args = array_slice($args,1);
switch($method_name) {
case 'foo':
case 'far':
//case .....
//write in log files
break;
}
//THEN, RELAY THE CALL TO THE INITIAL METHOD
}
}
#"dynamic" A.php
class A extends Logger {
public function foo($log_level, $bar) {
echo ' // Hello there !';
}
public function bar($foo) {
echo " $ù$ùmezf$z !";
}
}
#"dynamic" B.php
class B extends Logger {
public function far($log_level, $boo) {
echo $boo;
}
}
The big challenge here is to transform A and B into their "dynamic" versions, once the XML parser has completed its job.
The ideal would be to achieve that without modifying the code of A and B at all (I mean, in the files) - or at least find a way to come back to their original versions once the program is finished.
To be clear, I wanna find the most proper way to intercept method calls in PHP.
What are your ideas about it ???
Thanks in advance,
Rolf