PHP Memory Limit Detection with ZF
So, you got your web application up and running? Everything works? Congratulations! You did a great job. But do you know how your web app will behave if the number of users or requests increases dramatically? Are you sure that there are no memory leaks in your application?
Well, if you are not sure this post might help you. The idea is basically very simple: we will implement a Zend Framework plugin which checks the memory used by a request. If the request consumes for instance more than 70% of the memory available to PHP, we will do something (e.g, write a log entry, send an email to the admin or send a prayer to the Lord).
<?php
/**
* ZF Plugin which checks, if memory consumed is greater then a defined amount. If so: log an alert.
* Based on code published at http://www.phpgangsta.de/fruhzeitig-memory-limit-probleme-entdecken
*
* @package Web_Punk
* @author Christian Koncilia
*/
class Webpunk_Plugin_CheckMemoryUsage extends Zend_Controller_Plugin_Abstract
{
// send a warning to the admin if this limit in percent (here, 70%) is reached.
const WARNING_LIMIT = 0.7;
public function dispatchLoopShutdown()
{
if (memory_get_peak_usage() > $this->getBytes(ini_get('memory_limit')) * self::WARNING_LIMIT) {
$body = "Peak usage: ".memory_get_peak_usage() .
" memory_limit: ".ini_get('memory_limit').
" Request: ".$_SERVER["REQUEST_URI"];
// Write log entry (you might want to replace these lines and insert your ToDo-code here)
$writer = new Zend_Log_Writer_Stream ( "mylogfile.log" );
$logger = new Zend_Log ();
$logger->addWriter ( $writer );
$logger->alert($body);
}
}
private function getBytes($val) {
$val = trim($val);
$last = strtolower($val{strlen($val)-1});
switch($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
}
Now, all you have to do is to register the plugin in your frontend controller by adding something like this to your application.ini:
resources.frontController.plugins.checkmem = "Webpunk_Plugin_CheckMemoryUsage"
Related posts:

CSS Zend Garden
KingCrunchs kleine Welt