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.

4 comments:

Anonymous said...

>> I have been using register_shutdown_function for years now, especially to clean up connections at the end of script execution.

why it is needed to clean up connections at the end of script execution? for mysql, I suppose it is not needed

Anonymous said...

as long as you dont use persistent connections. even still you might want to check if there are still open transactions, which would incicate issues in your code, that need to be fixed even if they are not going to do damage in the next request.

Anonymous said...

i also run in the __destuct problem with db access.
i wanted to write changes back to db, but alway got an error that my db object is already destructed.

i just workarrounded this with a save() method and i think this was the cleaner way, but i'm a programmer, im lazy so i will try to get this workign in my classes.

good post/information thx.

Anonymous said...

Hi,

Hope you're doing great!

Our direct client is looking for a MySQL DBA for 6 months contract in Alpharetta, GA.


Please send me your resume along with billing rate and contact details, if you're interested.


Job Title: MySQL DBA
Job Location: Alpharetta, GA.
Duration: 6 months contract


Thanks and regards,
Ashutosh Baranwal
Primus Software Corporation
Tel: 678-935-3554
Fax: 678-336-1505
ashutosh@primussoft.com
www.primussoft.com