PHP - 禁用只在开发中需要的类

时间:2016-06-16 00:15:08

标签: php design-patterns architecture

我正在用PHP编写一个小脚本,并且正在使用开发区的Profiler来查看哪些函数/操作很慢等。

$this->profiler = new \Fabfuel\Prophiler\Profiler();

然后我在不同的方法中使用它(通过DI传递它,使用League \ Container \ Container类):

$profilerSeg = $profiler->profilerStartSegment('Page Load','CMS');
...
$profiler->profilerStopSegment($profilerSeg);

问题是,我只想在开发中使用它。关于IF声明的想法:

if($this->environment === 'DEV')
    $profilerSeg = $profiler->profilerStartSegment('Page Load','CMS');
...
if($this->environment === 'DEV')
    $profiler->profilerStopSegment($profilerSeg);

但到处都看起来很难看。然后我想到制作一个假的探测器"如果脚本处于生产状态,则会传递,因此所有调用都将返回NULL。

处理这种情况的最佳方法是什么:只在开发中需要的类,但不应该在生产中加载?

1 个答案:

答案 0 :(得分:1)

典型的oop使用继承

大多数方法定义了所有(或大多数)其他类扩展的根类

Class main {
    private $profiler;

    public __construct(){
        $this->profiler = new \Fabfuel\Prophiler\Profiler();
        // you can comment and uncomment the above line.
    }

    public profStart(){
        if (!empty($this->profiler)) {
            $this->profiler->profilerStartSegment($a,$b);
        }
    }
}

Class someThing Extends main {
     // $profiler is already set as part of the constructor
     $this->profStart('someThing','strange');
}

Class otherThing Extends someThing {
     // but if you want a constructor, you have to daisy-chain the class constructors
     public __construct() {
          parent::__construct();
     }
}

或者,换出一个空对象

......但这通常被认为是不好的做法

Class deadendObject {
     public __get($var){}
     public __set($var,$val){}
     public __call($var,$args){}
     // see: http://php.net/manual/en/language.oop5.magic.php
}

if ($profileMe) {
     $this->profiler = new \Fabfuel\Prophiler\Profiler();
} else {
     $this->profiler = new deadendObject();
}

设置是否在Profiler对象本身中执行操作

Class Profiler {
    public $enabled = true;

    public function doSomething(){
         if($this->enabled) {
              // do stuff
         }
    }
}

$profiler = new \Fabfuel\Prophiler\Profiler();
$profiler->enabled = false;

Best是继承的组合,并且使得探查器处理行为发生了变化。

Class Profiler {
    public $enabled = true;

    public function doSomething($var = "unknown"){
         if($this->enabled) {
              // do stuff
         }
    }
}

Class main {
    public $profiler;

    public __construct(){
        $this->profiler = new Profiler();
        $this->profiler->enabled = true;
        // better still would be to define this behavior according to a settings file, or environment variables with getenv()
    }
}

Class someThing Extends main {
     // $profiler is already set as part of the constructor
     $this->profiler->doSomething('neighborhood');
}

我不怕'没有鬼!