Yii2在API中设置活动用户

时间:2015-11-20 03:55:59

标签: yii2

在Yii 1中,我在API控制器中使用此代码来设置活动用户:

        $.getJSON( "getlayers.php", function( data ) {
        var product = $("#multipleselectlist");
            $.each(data, function (key, cat) {
            var group = {};
            group['id'] = '';
            group['text'] = key;
            var children = [];
            $.each(cat,function(i,item) {
                var options = {};
                options['key'] = key;
                options['value'] = item.color;
                options['text'] = item.location;
                options['id'] = item.filename;
                children.push(options);
                });
            group['children'] = children;
            layer_group.push(group);
        });
    });

          $('#multipleselectlist').select2({ formatResult: getIcon, formatSelection: getIconSel, placeholder: "Select any layers",
          multiple: true,
          placeholder: "Select any layer",
          dropdownAutoWidth: true,
          data: layer_group,
          query: function(options) {
              var selectedIds = options.element.select2('val');
              var selectableGroups = $.map(this.data, function(group) {
                  var areChildrenAllSelected = true;
                  $.each(group, function(i, child) {
                      if (selectedIds.indexOf(child.id) < 0) {
                          areChildrenAllSelected = false;
                          return false; // Short-circuit $.each()
                      }
                 });
                  return !areChildrenAllSelected ? group : null;
              });
              options.callback({ results: selectableGroups });
          }
        })

但是在Yii2中,这是不允许的,因为Yii :: $ app-&gt; user-&gt; id现在是只读的。

设置活动用户ID的等效命令是什么?

1 个答案:

答案 0 :(得分:2)

您需要对API使用setIdentity()方法:

use Yii;

...

Yii::$app->user->setIdentity($user)
  

setIdentity():更改用户身份而不触及会话或   曲奇饼。这最适用于无状态RESTful API实现。

其中$user应该是User模型的有效实例。

如果您需要更改现有用户,请改用switchIdentity()方法:

use Yii;

...

Yii::$app->user->switchIdentity($user)