Yii2 Call api method from backend controllers

2020-04-08 12:27发布

问题:

I have implemented API based on advanced template following Yii Rest API documentation. And I want to call API methods from backend controllers. Is it possible to do?

Thanks

回答1:

So, I finally found a solution.

My Yii2 application has advanced template. I've created api module.

So app has 3 endpoints

  • api
  • backend
  • frontend

And I wanted to call api methods from backend or frontend, It's not important.

So the main goal here that api is the module. You can read about this 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');

That how it works. Hope it will help to someone.



回答2:

A way could be this .

Assuming that you rest controller is in frontend

In your backend application config you could create an additional 'UrlManager' component name eg: 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,
      ],

  ],
];

Then you should invoke following to compose URL:

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


回答3:

you can use postman for testing your api. first download your version of postman then choose your method. then determine your inputs and your url. and finally press send button. your url might be like

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

that yourdomain.com is your domain and yourController are controller and yourAction are your action.



标签: rest api yii2