O'Reilly logo

Yii2 By Example by Fabrizio Caldarelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

New controller action

It is very simple to add new actions to the REST API controller. We only need to remember three differences in the web controller:

  • Verb setting for the new action
  • Authenticate the setting for the new action
  • Output for the new action

The first two steps are configured in the behaviors() method of the controller:

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['verbs'] = [
                'class' => \yii\filters\VerbFilter::className(),
                'actions' => [
                    'myCustomAction'  => ['get', 'head'],
                ],
        ];
        
        $behaviors['authenticator'] = [
        'except' => 'myCustomAction',
            'class' => HttpBasicAuth::className(),
        ];
      
        return $behaviors;
    }

public function actionMyCustomAction()
{
    …
    …
    
}

In the first part of the behaviors() method, we will only ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required