Enable debugger tool for particular user through custom controller in Yii2

可紊 提交于 2019-12-25 02:26:21

问题


To enable debugger tool, we modify web/index.php file

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

How to override or change these variables in custom controller?

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');
    }
  }
}

Goal is to enable the debugger for particular user. I know there is a way through AllowedIps. But, I was looking for particular user wise. Is it possible?


回答1:


Based on this article

Create a new Class somewhere, I used common\components\Debug. Extend it from yii\debug\Module and overwrite checkAccess()with your required logic.

<?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;
    }
}

Then update your main-local.php for the app(s) you need it

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

    ...
}

This will of course run the debugger for all users, but only display it for the administrators. This might have some unwanted overhead on your application, but the debugging process starts before the identity is checked.



来源:https://stackoverflow.com/questions/51668018/enable-debugger-tool-for-particular-user-through-custom-controller-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!