Reputation: 48
I am writing a small script in PHP and am using a Profiler for the development zone to see which functions/actions are slow etc.
$this->profiler = new \Fabfuel\Prophiler\Profiler();
Then I am using it in different methods all over the place (passing it via DI, using League\Container\Container class):
$profilerSeg = $profiler->profilerStartSegment('Page Load','CMS');
...
$profiler->profilerStopSegment($profilerSeg);
Problem is, I only want to use this in development. Thought about an IF statement:
if($this->environment === 'DEV')
$profilerSeg = $profiler->profilerStartSegment('Page Load','CMS');
...
if($this->environment === 'DEV')
$profiler->profilerStopSegment($profilerSeg);
but it looks ugly to have it everywhere. Then I thought about making a "fake profiler" that gets passed if the script is in production so all the calls would return NULL.
What is the best way to handle such a case: a class needed only in development but that should not be loaded in production?
Upvotes: 1
Views: 67
Reputation: 5683
Most approaches define a root class that all (or most) other classes extend
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();
}
Class Profiler {
public $enabled = true;
public function doSomething(){
if($this->enabled) {
// do stuff
}
}
}
$profiler = new \Fabfuel\Prophiler\Profiler();
$profiler->enabled = false;
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');
}
I ain't afraid 'o no ghosts!
Upvotes: 1