使用单例模式解决PHP耗尽服务器内存的问题

今天公司的项目出现了php超过了服务器内存限制的错误:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1792 bytes) in *****
后来发现Alert_Push_Main类中的main()是一个死循环观察者,一直在调用atom(),而atom()中的观察者类Alert_Push_Observer将一直被new即分配内存,我使用memory_get_usage()看了下内存的使用情况,每运行一次atom()会消耗1088bytes的内存,而这个main()是一个死循环,进程一直没有停止,导致这些内存没有释放掉,最终铸成了服务器内存耗尽的问题。
<?php
class Dzl_Alert_Push_Main
{
     public static function main()
     {
          while (true) {
               $weekday = date('w', strtotime(date('Y-m-d')));
               if (date('H:i:s') <= '15:00:00' 
               && date('H:i:s') >= '09:25:00'
               && $weekday != 0 && $weekday != 6) {
                    self::atom();
               } else {
                    //用于停掉观察者的死循环
                    break;
               }
          }
     }

     public static function atom()
     {
          $one = new Dzl_Alert_Push_Subject_Main();
          //下面这句是罪魁祸首!!!
          $observer = new Dzl_Alert_Push_Observer($one);
          $one->dealTrigger();
     }
}
解决方法:
这个时候我想到了单例模式,进程中只要一个Alert_Push_Observer对象就可以了:
<?php
class Dzl_Alert_Push_Main
{
     public static function main()
     {
          while (true) {
               $weekday = date('w', strtotime(date('Y-m-d')));
               if (date('H:i:s') <= '15:00:00' 
               && date('H:i:s') >= '09:25:00'
               && $weekday != 0 && $weekday != 6) {
                    self::atom();
               } else {
                    //用于停掉观察者的死循环
                    break;
               }
          }
     }

     public static function atom()
     {
          $one = new Dzl_Alert_Push_Subject_Main();
          //将下面这句改成了单例模式
          $observer = Dzl_Alert_Push_Observer::getInstance()->setSubject($one);
          $one->dealTrigger();
     }
}

Waterfall Model for Software Development(瀑布模型)

Advantage:

Provide milestones(提供里程碑。).

Provide data for schedule planning(提供日程安排的数据。).

Provide data for staff planning(提供员工安排的数据。).

The process looks rational(这个过程看起来是合理的。).

The model gives the manager confidence in the progress of the project.(这个模型让经理对这个项目的处理有信心。)

 

Disadvantage:

No room for feedback.(没有反馈的空间)

Present a management framework, not suitable for software development.(代表一个管理的框架,不适合软件开发)

Doesn't allow change.(不允许改变)

Real projects rarely sequential-iteration required.(真正的项目需求很少是顺序迭代的)

Difficulty in user stating all requirements early.(使用者早早地说明所有需求是困难的)

Working version of program not available until late in the life cycle.(可行的程序版本直到生命周期的末期才可以利用)

Developers often delayed-blocking states.(开发者经常处于延迟堵塞状态)

 

Tonitech版权所有 | 转载请注明出处: http://www.tonitech.com/?p=422