Using soap WebService in Yii2

Using soap WebService in yii2 is very simple. Some people have provided relevant extensions for us to use. Of course, we can also write by ourselves. Here is how to use soap in yii2 with extensions written by others

Note: the prerequisite for normal use of soap is to remember to open the soap extension of PHP

1. First install the SOAP Server Extension

1 composer require --prefer-dist mongosoft/yii2-soap-server "*"

a. You need to add [[mongosoft \ soapserver \ Action]] to your controller.

Note: in your service class, the callable method must be a public method containing the doc comment block of the '@ soap' tag

 1 class ApiController extends Controller
 2 {
 3     /**
 4      * @inheritdoc
 5      */
 6     public function actions()
 7     {
 8         return [
 9             'hello' => 'mongosoft\soapserver\Action',
10         ];
11     }
12 
13     /**
14      * @param string $name
15      * @return string
16      * @soap
17      */
18     public function getHello($name)
19     {
20         return 'Hello ' . $name;
21     }
22 }

b. If you want to disable the WSDL mode of SoapService, you can set it through the serviceOptions parameter

 1 /**
 2      * @inheritdoc
 3      */
 4     public function actions()
 5     {
 6         return [
 7             'index' => [
 8                 'class' => 'mongosoft\soapserver\Action',
 9                 'serviceOptions' => [
10                     'disableWsdlMode' => true,
11                 ]
12             ]
13         ];
14     }

2. Install soap client extensions

1 composer require --prefer-dist mongosoft/yii2-soap-client "*"

a. Configuration:

 1 'components' => [
 2     'siteApi' => [
 3         'class' => 'mongosoft\soapclient\Client',
 4         'url' => 'http://myservice.com/api/hello',
 5         'options' => [
 6             'cache_wsdl' => WSDL_CACHE_NONE,
 7         ],
 8     ]
 9     ...
10 ]

Or you can use it directly in your code:

1 $client = new \mongosoft\soapclient\Client([
2     'url' => 'http://myservice.com/api/hello',
3 ]);

b, use

1 $client = Yii::$app->siteApi;
2 echo $client->getHello('Alex');

 

You need to add [[mongosoft \ soapserver \ Action]] to the Web controller.

Tags: PHP

Posted on Sat, 04 Apr 2020 00:34:42 -0700 by sunnyk