Conditional Component Loading in CakePHP

2020-08-01 06:25发布

问题:

I'm using the DebugKit component in my project but I want to turn it on only on the staging server and have it not load when running from the production server.

I know I can turn it off with the debug config value but I want to keep that value at 1 for both servers.

I tried conditionally defining a contstant 'DEBUG_KIT' in bootstrap.php as either the component name (ie. 'DebugKit.Toolbar') or null. Then using that constant in the var $component definition at the top of the app_controller file. Well, Cake doesn't like having a null in the component array and barfs. Doesn't like an empty string either.

I feel like I'm missing something but can't quite see the forest for the trees. Thanks in advance!

回答1:

I do something similar in my apps: I would use the __construct method to detect the presence DEBUG_KIT and add it to the $components array. This function gets called before the $components array is processed, so you can add/remove components transparently.

In your app_controller

function __construct(){
  if(DEBUG_KIT){
    $this->components[] = 'DebugKit.Toolbar'
  }
  parent::__construct();
}

If you have a _construct function in any or your individual controllers, remember to include parent::_construct(); otherwise you'll 'break the chain'.

Hope this helps



回答2:

I think the fundamental purpose of DebugKit is tied to being in debug mode, so I can understand that the tools don't provide the capacity to be disabled without also disabling debug mode.

That said, if you absolutely must do this, I think your best bet is to directly modify app/plugins/debugkit/controllers/components/toolbar.php, supplementing the existing debug-mode check in ToolbarComponent::initialize with a check against your constant.

(For what it's worth, I think you'd be better off turning debug-mode off on your production server, and using errors/warnings logged in /app/tmp/logs/error.log to identify issues that have slipped through your testing.)



回答3:

First, thanks to Adam Giles for a great answer. I hadn't thought to look at the __construct() callback. That just may be a better way than I found. And to Daniel Wright, point made sir. I'll probably change my production server to 0 debug soon and start watching the error logs.

I found my own answer shortly after posting this question. The DebugKit has an 'autoRun' parameter that will turn it on and off. So, I first set a global constant in bootstrap.php like this:

define( 'IS_DEV', ($_SERVER['SERVER_NAME'] == 'staging.example.com') );

Then in app_controller.php, I use it to set the 'autoRun' parameter in the $components statement.

var $components = array( 'DebugKit.Toolbar'=>array('autoRun'=>IS_DEV) );

This seems to work pretty well so far.