Yii2 Call api method from base controllers

I implemented the API based on the extended template after the Yii Rest API documentation. And I want to call API methods from backend controllers. Can this be done?

thank

+4
source share
3 answers

So, I finally found a solution.

My Yii2 application has an advanced template. I created an api module.

So the application has 3 endpoints

  • api
  • backend
  • interface

And I wanted to call api methods from the backend or interface, it doesn’t matter.

So, the main goal here is api module . You can read about it here.

In backend / config / main.php

'modules' => [
    'api' => [
        'basePath' => '@api/modules/v1',
        'class' => 'api\modules\v1\Module'
    ]
],

And then for example

in backend / UserController / indexAction

$res = Yii::$app->runAction('api/user/index');

. , -.

+3

, .

,

backend- "UrlManager", : urlManagerForRest

return [
  'components' => [
      'urlManager' => [
          // here is your backend URL rules
      ],
      'urlManagerForRest' => [
          'class' => 'yii\web\urlManager',
          'baseUrl' => 'http://your_path/frontend/web/index.php',
          'enablePrettyUrl' => true,
          'showScriptName' => false,
      ],

  ],
];

URL-:

Yii::$app->urlManagerFrontEnd->createUrl();
+1

postman api. , . URL. , , . URL-

http://yourdomain.com/backend/web/index.php?r=yourController/yourAction

yourdomain.com - , yourController - , yourAction - .

-1

Source: https://habr.com/ru/post/1673842/


All Articles