Tuesday, December 16, 2008

Logging to DB after PHP is done generating content

Oh how I love register_shutdown_function of PHP. This bad baby will execute at the end of the scripts in call order. So, how is this useful?

Say you want to log some action, but that logging DB is on another server. Additionally you do not want to take into account that writing to the other server may break your transaction because of timeouts if logged in the middle of a transaction. Another use case: you do not want to change a bunch of code in different places to batch all logging routines up.


public function __construct($platform){
parent::__construct($platform);
register_shutdown_function(array($this, 'afterProcess'));
}


public function afterProcess(){

foreach($this->getDataThatChange() as $key => $values){
$insert_data[] = $values;
}

$this->getDBClass()->DB_logserver_insert_query("LoggingTable", $insert_data, 'delayed');


}


The function afterProcess will batch all the changes and do a bulk insert into a myISAM table so it can used the DELAYED functionality.

This is done outside of all transactions, and at the end of the script as the data is returned.

But, why not just use __deconstructor() in PHP? I want it to happen before the deconstructor is called.

http://us3.php.net/manual/en/language.oop5.decon.php#76710

I have been using register_shutdown_function for years now, especially to clean up connections at the end of script execution. Since someone asked me if this was possible in PHP, I decided to post this quick usage of a cool php method.