创建一个简单的SOAP服务器

和SOAP客户端一样,我们可以使用PHP SOAP扩展来实现一个SOAP服务器。实现中最困难的部分是从API类生成WSDL。我们不在这里介绍这个过程,因为有很多好的WSDL生成器可用。

如何做…

1.首先,你需要一个将由SOAP服务器处理的API。在这个例子中,我们定义了一个Application\Web\Soap\ProspectsApi类,它允许我们创建、读取、更新和删除prospects表。

  1. namespace Application\Web\Soap;
  2. use PDO;
  3. class ProspectsApi
  4. {
  5. protected $registerKeys;
  6. protected $pdo;
  7. public function __construct($pdo, $registeredKeys)
  8. {
  9. $this->pdo = $pdo;
  10. $this->registeredKeys = $registeredKeys;
  11. }
  12. }
  1. 然后我们定义方法,分别对应创建、读取、更新和删除。在这个例子中,这些方法被命名为put()get()post()delete()。这些方法依次调用产生SQL请求的方法,这些请求将从PDO实例中执行。get()的例子如下。
  1. public function get(array $request, array $response)
  2. {
  3. if (!$this->authenticate($request)) return FALSE;
  4. $result = array();
  5. $id = $request[self::ID_FIELD] ?? 0;
  6. $email = $request[self::EMAIL_FIELD] ?? 0;
  7. if ($id > 0) {
  8. $result = $this->fetchById($id);
  9. $response[self::ID_FIELD] = $id;
  10. } elseif ($email) {
  11. $result = $this->fetchByEmail($email);
  12. $response[self::ID_FIELD] = $result[self::ID_FIELD] ?? 0;
  13. } else {
  14. $limit = $request[self::LIMIT_FIELD]
  15. ?? self::DEFAULT_LIMIT;
  16. $offset = $request[self::OFFSET_FIELD]
  17. ?? self::DEFAULT_OFFSET;
  18. $result = [];
  19. foreach ($this->fetchAll($limit, $offset) as $row) {
  20. $result[] = $row;
  21. }
  22. }
  23. $response = $this->processResponse(
  24. $result, $response, self::SUCCESS, self::ERROR);
  25. return $response;
  26. }
  27. protected function processResponse($result, $response,
  28. $success_code, $error_code)
  29. {
  30. if ($result) {
  31. $response['data'] = $result;
  32. $response['code'] = $success_code;
  33. $response['status'] = self::STATUS_200;
  34. } else {
  35. $response['data'] = FALSE;
  36. $response['code'] = self::ERROR_NOT_FOUND;
  37. $response['status'] = self::STATUS_500;
  38. }
  39. return $response;
  40. }

3.然后你可以从你的 API 中生成一个 WSDL。有很多基于 PHP 的 WSDL 生成器可以使用。大多数需要你在将要发布的方法之前添加 phpDocumentor 标签。在我们的例子中,两个参数都是数组。这里是前面讨论的 API 的完整 WSDL。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <wsdl:definitions xmlns:tns="php7cookbook" targetNamespace="php7cookbook" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
  3. <wsdl:message name="getSoapIn">
  4. <wsdl:part name="request" type="tns:array" />
  5. <wsdl:part name="response" type="tns:array" />
  6. </wsdl:message>
  7. <wsdl:message name="getSoapOut">
  8. <wsdl:part name="return" type="tns:array" />
  9. </wsdl:message>
  10. <!—some nodes removed to conserve space -->
  11. <wsdl:portType name="CustomerApiSoap">
  12. <!—some nodes removed to conserve space -->
  13. <wsdl:binding name="CustomerApiSoap" type="tns:CustomerApiSoap">
  14. <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc" />
  15. <wsdl:operation name="get">
  16. <soap:operation soapAction="php7cookbook#get" />
  17. <wsdl:input>
  18. <soap:body use="encoded" encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/" namespace="php7cookbook" parts="request response" />
  19. </wsdl:input>
  20. <wsdl:output>
  21. <soap:body use="encoded" encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/" namespace="php7cookbook" parts="return" />
  22. </wsdl:output>
  23. </wsdl:operation>
  24. <!—some nodes removed to conserve space -->
  25. </wsdl:binding>
  26. <wsdl:service name="CustomerApi">
  27. <wsdl:port name="CustomerApiSoap" binding="tns:CustomerApiSoap">
  28. <soap:address location="http://localhost:8080/" />
  29. </wsdl:port>
  30. </wsdl:service>
  31. </wsdl:definitions>

4.接下来,创建一个chap_07_simple_soap_server.php文件,它将执行SOAP服务器。首先定义WSDL和其他必要文件的位置(在本例中,一个是数据库配置文件)。如果设置了wsdl参数,那么就传递WSDL而不是尝试处理请求。在这个例子中,我们使用一个简单的API密钥来验证请求。然后我们创建一个SOAP服务器实例,分配一个API类的实例,并运行handle()

  1. <?php
  2. define('DB_CONFIG_FILE', '/../config/db.config.php');
  3. define('WSDL_FILENAME', __DIR__ . '/chap_07_wsdl.xml');
  4. if (isset($_GET['wsdl'])) {
  5. readfile(WSDL_FILENAME);
  6. exit;
  7. }
  8. $apiKey = include __DIR__ . '/api_key.php';
  9. require __DIR__ . '/../Application/Web/Soap/ProspectsApi.php';
  10. require __DIR__ . '/../Application/Database/Connection.php';
  11. use Application\Database\Connection;
  12. use Application\Web\Soap\ProspectsApi;
  13. $connection = new Application\Database\Connection(
  14. include __DIR__ . DB_CONFIG_FILE);
  15. $api = new Application\Web\Soap\ProspectsApi(
  16. $connection->pdo, [$apiKey]);
  17. $server = new SoapServer(WSDL_FILENAME);
  18. $server->setObject($api);
  19. echo $server->handle();

{% hint style=”info” %} 根据你的php.ini文件的设置,你可能需要禁用WSDL缓存,如下所示。

  1. ini_set('soap.wsdl_cache_enabled', 0);

如果传入的POST数据有问题,可以按以下方式调整这个参数。

  1. ini_set('always_populate_raw_post_data', -1);

{% endhint %}

如何运行…

你可以首先创建你的目标API类,然后生成一个WSDL来轻松测试这个事例。然后,你可以使用内置的PHP webserver来交付SOAP服务,使用这个命令。

  1. php -S localhost:8080 chap_07_simple_soap_server.php

然后,你可以使用前面事例中讨论的SOAP客户端来调用测试SOAP服务。

  1. <?php
  2. define('WSDL_URL', 'http://localhost:8080?wsdl=1');
  3. $clientKey = include __DIR__ . '/api_key.php';
  4. try {
  5. $client = new SoapClient(WSDL_URL);
  6. $response = [];
  7. $email = some_email_generated_by_test;
  8. $email = 'test5393@unlikelysource.com';
  9. echo "\nGet Prospect Info for Email: " . $email . "\n";
  10. $request = ['token' => $clientKey, 'email' => $email];
  11. $result = $client->get($request,$response);
  12. var_dump($result);
  13. } catch (SoapFault $e) {
  14. echo 'ERROR' . PHP_EOL;
  15. echo $e->getMessage() . PHP_EOL;
  16. } catch (Throwable $e) {
  17. echo 'ERROR' . PHP_EOL;
  18. echo $e->getMessage() . PHP_EOL;
  19. } finally {
  20. echo $client->__getLastResponse() . PHP_EOL;
  21. }

以下是电子邮件地址test5393@unlikelysource.com 的输出。

创建一个简单的SOAP服务器 - 图1

更多…

简单的谷歌搜索PHP的WSDL生成器,很容易就得到了十几个结果。用来生成ProspectsApi类的WSDL的是基于https://code.google.com/archive/p/php-wsdl-creator/。关于phpDocumentor的更多信息,请参考https://www.phpdoc.org/