如何在yii2中允许用户以访客身份访问特定控制器

时间:2018-06-21 07:44:26

标签: yii2

我正在做一个Yii基础项目,我有一个搜索控制器,我希望允许所有登录用户和来宾用户访问。我不需要用户登录即可搜索项目,因此我想免除此控制器,因为当我尝试访问此控制器时,我已重定向到登录页面。

我的控制器在下面

    class SearchController extends \yii\web\Controller
{

     public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index'],
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                ],
            ],

        ];
    }

    public function actionIndex()
    {

        $params = 'product_id,title, price,unit_sold,state,city,profile_img,store_name,item_number,slug';
        $model= Products::find()->select($params)->asArray()->all();

        //print_r($model); exit;
        //check if model has value and loop through the value else set the value to empty array
        //to avoid throwing  undefine error
        if(isset($model) && !empty($model)){
            foreach($model as $v){
           $data[] = $v;
          }
        }else{
           $data[] = []; 
        }

        return $this->render('index',[
            'data' => $data,
        ]);

    }

}

,路由为http//www.mysite.com/search/index,在我以匿名用户身份访问该路由后,我被重定向到http//www.mysite.com/site/login

注意:最初没有行为方法,我将其添加为解决此问题的方法,但是直到我被重定向

1 个答案:

答案 0 :(得分:1)

引用Yii2 AccessControl

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['index'],
                    'allow' => true,
                ],
            ],
        ],
    ];
}

如果您使用了mdmsoft/yii2-admin,则将以下代码添加到config/web.php

use mdm\admin\components\AccessControl;

return [
   'components' => [
       'as access' => [
           'class' => AccessControl::class,
           'allowActions' => [
                 'search/index',
            ],
       ],
    ]
];