PHP code example of tunecino / yii2-nested-rest

1. Go to this page and download the library: Download tunecino/yii2-nested-rest library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tunecino / yii2-nested-rest example snippets


'rules' => [
    [
        // Yii defaults REST UrlRule class
        'class' => 'yii\rest\UrlRule',
        'controller' => ['team','player','skill'],
    ],
    [
        // The custom UrlRule class
        'class' => 'tunecino\nestedrest\UrlRule',
        'modelClass' => 'app\models\Team',
        'relations' => ['players'],
    ],
    [
        'class' => 'tunecino\nestedrest\UrlRule',
        'modelClass' => 'app\models\Player',
        'relations' => ['team','skills'],
    ],
]

'rules' => [
    [
        /**
         * the custom UrlRule class
         */
        'class' => 'tunecino\nestedrest\UrlRule', /*        * relations names to be nested with this model
         * they should be already defined in the model's Active Record class.
         * check the below section for more about advanced configurations.
         */
        'relations' => ['team','skills'], /* using 'controller => ['teams' => 'v1/team']'
         *  instead of 'controller => ['team']'
         */
        'modulePrefix' => 'v1', /* optional */
        /**
         * the default list of tokens that should be replaced for each pattern.
        */
        'tokens' => [ /* optional */
            '{id}' => '<id:\\d[\\d,]*>',
            '{IDs}' => '<IDs:\\d[\\d,]*>',
        ],
        /**
         * The Regular Expressions Syntax used to parse the id of the main resource from url.
         * For example, in the following final rule, $linkAttributePattern is default to that `\d+` to parse $brand_id value:
         *
         *     GET,HEAD v1/brands/<brand_id:\d+>/items/<IDs:\d[\d,]*>
         *
         * While that works fine with digital IDs, in a system using a different format, like uuid for example,
         * you may use $linkAttributePattern to define different patterns. Something like this maybe:
         *
         * [
         *       // Nested Rules Brand
         *      'class' => 'tunecino\nestedrest\UrlRule',
         *      'modelClass' => 'app\modules\v1\models\Brand',
         *      'modulePrefix' => 'v1',
         *      'resourceName' => 'v1/brands',
         *      'relations' => ['items'],
         *      'tokens' => [
         *          '{id}' => '<id:[a-f0-9]{8}\\-[a-f0-9]{4}\\-4[a-f0-9]{3}\\-(8|9|a|b)[a-f0-9]{3}\\-[a-f0-9]{12}>',
         *          '{IDs}' => '<IDs:([a-f0-9]{8}\\-[a-f0-9]{4}\\-4[a-f0-9]{3}\\-(8|9|a|b)[a-f0-9]{3}\\-[a-f0-9]{12}(?:,|$))*>',
         *      ],
         *      'linkAttributePattern' => '[a-f0-9]{8}\\-[a-f0-9]{4}\\-4[a-f0-9]{3}\\-(8|9|a|b)[a-f0-9]{3}\\-[a-f0-9]{12}',
         *  ],
        */
        'linkAttributePattern' => '\d+', /* optional */
        /**
         *  the default list of patterns. they may all be overridden here
         *  or just edited within $only, $except and $extraPatterns properties
         */
        'patterns' => [ /* optional */
            'GET,HEAD {IDs}' => 'nested-view',
            'GET,HEAD' => 'nested-index',
            'POST' => 'nested-create',
            'PUT {IDs}' => 'nested-link',
            'DELETE {IDs}' => 'nested-unlink',
            'DELETE' => 'nested-unlink-all',
            '{id}' => 'options',
            '' => 'options',
        ],
        /**
         *  list of acceptable actions.
         */
        'only' => [], /* optional */
        /**
         *  actions that should be excluded.
         */
        'except' => [], /* optional */
        /**
         *  supporting extra actions in addition to those listed in $patterns.
         */
        'extraPatterns' => [] /* optional */
    ],
]

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

    $actions['nested-index'] = [
        'class' => 'tunecino\nestedrest\IndexAction', /* iew'] = [
        'class' => 'tunecino\nestedrest\ViewAction', /*  /* .
         */
        'scenario' => 'default', /* optional */
        /**
         * the scenario to be assigned to the model class responsible
         * of handling the data stored in the juction table.
         */
        'viaScenario' => 'default', /* optional */
        /**
         * expect junction table related data to be wrapped in a sub object key in the body request.
         * In the example we gave above we would need to do :
         * POST {name: 'dribble', related: {level: 10}}
         * instead of {name: 'dribble', level: 10}
         */
        'viaWrapper' => 'related' /* optional */
    ];

    $actions['nested-link'] = [
        'class' => 'tunecino\nestedrest\LinkAction', /* 

// GET /players/1/junior-coaches => should route to 'JuniorCoachController'
'relations' => ['players','juniorCoaches'] // how it works by default

// GET /players/1/junior-coaches => should route to 'JuniorCoachesController'
'relations' => [
    'players',
    'juniorCoaches' => 'junior-coaches' // different controller name
]

// GET /players/1/juniors => should route to 'JuniorCoachesController'
'relations' => [
    'players',
    'juniorCoaches' => ['juniors' => 'junior-coaches'] // different endpoint name and different controller name
]

  $model->load($bodyParams);
  $viaModel->load($bodyParams);
  /* Scenarios can also be assigned to both models. when attaching actions. see configuration section */
  

relativeClass = 'app/models/player'; // the class name of the relative model
relationName  = 'skills'; // the one you did set in rules configuration.
linkAttribute = 'player_id'; // the foreign key attribute name.
player_id     = 9; // the foreign key attribute and its value

// junction table related method. usually auto generated by gii.
public function getSkillHasPlayers()
{
    return $this->hasMany(SkillHasPlayer::className(), ['skill_id' => 'id']);
}

protected function getSharedData()
{
    $params = Yii::$app->request->queryParams;
    $player_id = empty($params['player_id']) ? null : $params['player_id'];

    return ($player_id) ? $this->getSkillHasPlayers()
                             ->where(['player_id' => $player_id ])
                             ->select('level')
                             ->one() : null;
}

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

    if (!empty(Yii::$app->request->queryParams['player_id'])) {
        $fields['_shared'] = 'sharedData';
    }

    return $fields;
}