Search code examples
restdebuggingyii2profiler

How to use Yii2 debugger when developing RESTful application?


Like in the guide, I have created RESTful controller UserController.

namespace app\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
}

And when I make request GET /users, it works.

But I have no idea what queries does Yii2 execute behind the scene, and I do not know how long do they last.

Can I somehow use Yii2 debugger to debug and profile queries ? If not, what is the alternative for this ?


Solution

  • To see requests in Debugger for APIs

    1. Add this in you API config file -

      $config = [
          'id' => 'app-api',
          'basePath' => dirname(__DIR__),    
          'bootstrap' => ['log'],
          ......
          ....
      ]
      if (YII_ENV_DEV) {
          // configuration adjustments for 'dev' environment
          $config['bootstrap'][] = 'debug';
          $config['modules']['debug'] = [
              'class' => 'yii\debug\Module',
              'allowedIPs' => ['your_ip_address'], // accessible to this ip address only
          ];
      
          $config['bootstrap'][] = 'gii';
          $config['modules']['gii'] = [
              'class' => 'yii\gii\Module',
          ];
      }
      
      return $config;
      
    2. In web/index.php of API folder -

      defined('YII_DEBUG') or define('YII_DEBUG', true);
      defined('YII_ENV') or define('YII_ENV', 'dev');
      
    3. Access debugger by below URL-

      http://localhost/yii2-app/api/web/debug/default/view
      

    To change API's default actions like - create,update,view,index,delete
    write below code in controller

    /* Declare actions supported by APIs (Added in api/modules/v1/components/controller.php too) */
        public function actions(){
            $actions = parent::actions();
            unset($actions['create']);
            unset($actions['update']);
            unset($actions['delete']);
            unset($actions['view']);
            unset($actions['index']);
            return $actions;
        }
    
        /* Declare methods supported by APIs */
        protected function verbs(){
            return [
                'create' => ['POST'],
                'update' => ['PUT', 'PATCH','POST'],
                'delete' => ['DELETE'],
                'view' => ['GET'],
                'index'=>['GET'],
            ];
        }
        public function actionCreate(){echo "in create action";die;}