通过 Yii2 中的自定义控制器为特定用户启用调试器工具

Enable debugger tool for particular user through custom controller in Yii2

要启用调试器工具,我们修改 web/index.php 文件

defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'prod');

如何在自定义控制器中覆盖或更改这些变量?

class CommonController extends Controller {
  public function init() {
    $user_id = 1;
    if($user_id == 1){
      defined('YII_DEBUG') or define('YII_DEBUG', true);
      defined('YII_ENV') or define('YII_ENV', 'dev');
    }
  }
}

目标是为特定用户启用调试器。我知道有办法通过 AllowedIps。但是,我一直在寻找特定的用户。可能吗?

Based on this article

在某处新建Class,我用的是common\components\Debug。从 yii\debug\Module 扩展它并用您需要的逻辑覆盖 checkAccess()

<?php

namespace common\components;

class Debug extends \yii\debug\Module
{
    private $_basePath;

    protected function checkAccess()
    {
        $user = \Yii::$app->getUser();

        if (
            $user->identity &&
            $user->can('admin')
        ) {    
            return true;
        }
        //return parent::checkAccess();
    }

    /**
     * @return string root directory of the module.
     * @throws \ReflectionException
     */
    public function getBasePath()
    {
        if ($this->_basePath === null) {
            $class = new \ReflectionClass(new \yii\debug\Module('debug'));
            $this->_basePath = dirname($class->getFileName());
        }

        return $this->_basePath;
    }
}

然后为您需要的应​​用更新 main-local.php

if (!YII_ENV_TEST) {
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'common\components\Debug', // <--- Here
    ];

    ...
}

这当然会 运行 所有用户的调试器,但只对管理员显示。这可能会给您的应用程序带来一些不必要的开销,但调试过程会在检查身份之前启动。