Oleshek
Oleshek

Reputation: 95

Yii2 disable debug toolbar on specific domain

I need to dynamically show or hide this tool bar depending on the domain. But don't know how to do this in Yii2. Is it possible? this toolbar

Upvotes: 0

Views: 623

Answers (3)

Luna
Luna

Reputation: 2322

You need to inherit \yii\debug\Module and override the bootstrap method.

Add a judgment condition to $app->getView()->on(View::EVENT_END_BODY, [$this,'renderToolbar']); in the bootstrap method, if \Yii::$app->request->hostName is the domain name you specify, skip this line. Example:

if ('www.example.com' !== \Yii::$app->request->hostName) {
    $app->getView()->on(View::EVENT_END_BODY, [$this,'renderToolbar']);
}

Finally, the debug module uses your own class

UPDATE:

To provide you with a simple example:

// Module.php
<?php

namespace my/test/debug;

class Module extends \yii\debug\Module {
    public function bootstrap($app) {
        // other code
        
        $app->on(Application::EVENT_BEFORE_REQUEST, function () use ($app) {
            if ('www.example.com' !== \Yii::$app->request->hostName) {
                $app->getView()->on(View::EVENT_END_BODY, [$this,'renderToolbar']);
            }
            $app->getResponse()->on(Response::EVENT_AFTER_PREPARE, [$this, 'setDebugHeaders']);
        });
        
        // other code
    }
}

// config/main.php or config/main-local.php
'modules' => [
    'debug' => [
        'class' => \my\test\debug\Module::class,
    ],
],

Upvotes: 0

vvpanchev
vvpanchev

Reputation: 577

In your config/main-local.php it's supposed you have this:

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
    ];
    $config['modules']['debug']['allowedIPs'] = ['*'];
}

So you have to change your environment to production in your file web/index.php

change this:

defined('YII_ENV') or define('YII_ENV', 'dev');

to

if ('www.example.com' == $_SERVER['HTTP_HOST']) {
    defined('YII_ENV') or define('YII_ENV', 'prod'); //set production mode of application
}

dump($_SERVER['HTTP_HOST']) to see what is return :)

Or just add check in this file config/main-local.php

Upvotes: 0

Urmat Zhenaliev
Urmat Zhenaliev

Reputation: 1547

Try to put in your layout file:

if (class_exists('yii\debug\Module') && yii\helpers\Url::base() === '/my.domain') {
    $this->off(\yii\web\View::EVENT_END_BODY, [\yii\debug\Module::getInstance(), 'renderToolbar']);
}

But I suggest you to orient on environment value rather domain value. Because domains could be changed by time...

Upvotes: 0

Related Questions