A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.yiiframework.com/doc/guide/2.0/en/rest-controllers below:

RESTful Web Services: Controllers | The Definitive Guide to Yii 2.0

Controllers

After creating the resource classes and specifying how resource data should be formatted, the next thing to do is to create controller actions to expose the resources to end users through RESTful APIs.

Yii provides two base controller classes to simplify your work of creating RESTful actions: yii\rest\Controller and yii\rest\ActiveController. The difference between these two controllers is that the latter provides a default set of actions that are specifically designed to deal with resources represented as Active Record. So if you are using Active Record and are comfortable with the provided built-in actions, you may consider extending your controller classes from yii\rest\ActiveController, which will allow you to create powerful RESTful APIs with minimal code.

Both yii\rest\Controller and yii\rest\ActiveController provide the following features, some of which will be described in detail in the next few sections:

yii\rest\ActiveController in addition provides the following features:

Creating Controller Classes

When creating a new controller class, a convention in naming the controller class is to use the type name of the resource and use singular form. For example, to serve user information, the controller may be named as UserController.

Creating a new action is similar to creating an action for a Web application. The only difference is that instead of rendering the result using a view by calling the render() method, for RESTful actions you directly return the data. The serializer and the response object will handle the conversion from the original data to the requested format. For example,

public function actionView($id)
{
    return User::findOne($id);
}
Filters

Most RESTful API features provided by yii\rest\Controller are implemented in terms of filters. In particular, the following filters will be executed in the order they are listed:

These named filters are declared in the behaviors() method. You may override this method to configure individual filters, disable some of them, or add your own filters. For example, if you only want to use HTTP basic authentication, you may write the following code:

use yii\filters\auth\HttpBasicAuth;

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpBasicAuth::class,
    ];
    return $behaviors;
}
CORS

Adding the Cross-Origin Resource Sharing filter to a controller is a bit more complicated than adding other filters described above, because the CORS filter has to be applied before authentication methods and thus needs a slightly different approach compared to other filters. Also authentication has to be disabled for the CORS Preflight requests so that a browser can safely determine whether a request can be made beforehand without the need for sending authentication credentials. The following shows the code that is needed to add the yii\filters\Cors filter to an existing controller that extends from yii\rest\ActiveController:

use yii\filters\auth\HttpBasicAuth;

public function behaviors()
{
    $behaviors = parent::behaviors();

    
    $auth = $behaviors['authenticator'];
    unset($behaviors['authenticator']);
    
    
    $behaviors['corsFilter'] = [
        'class' => \yii\filters\Cors::class,
    ];
    
    
    $behaviors['authenticator'] = $auth;
    
    $behaviors['authenticator']['except'] = ['options'];

    return $behaviors;
}
Extending ActiveController

If your controller class extends from yii\rest\ActiveController, you should set its modelClass property to be the name of the resource class that you plan to serve through this controller. The class must extend from yii\db\ActiveRecord.

Customizing Actions

By default, yii\rest\ActiveController provides the following actions:

All these actions are declared through the actions() method. You may configure these actions or disable some of them by overriding the actions() method, like shown the following,

public function actions()
{
    $actions = parent::actions();

    
    unset($actions['delete'], $actions['create']);

    
    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

    return $actions;
}

public function prepareDataProvider()
{
    
}

Please refer to the class references for individual action classes to learn what configuration options are available.

Performing Access Check

When exposing resources through RESTful APIs, you often need to check if the current user has the permission to access and manipulate the requested resource(s). With yii\rest\ActiveController, this can be done by overriding the checkAccess() method like the following,


public function checkAccess($action, $model = null, $params = [])
{
    
    
    if ($action === 'update' || $action === 'delete') {
        if ($model->author_id !== \Yii::$app->user->id)
            throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
    }
}

The checkAccess() method will be called by the default actions of yii\rest\ActiveController. If you create new actions and also want to perform access check, you should call this method explicitly in the new actions.

Tip: You may implement checkAccess() by using the Role-Based Access Control (RBAC) component.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4