In ubuntu to install
php_soap
on PHP7 use below commands. Referencesudo apt-get install php7.0-soap
en mi caso que tengo instalado php7.2:
sudo apt-get install php7.2-soap
Crear una carpeta dentro de htdocs:
mkdir hello
Install the zend-soap library:
composer require zendframework/zend-soap
Creating a SOAP Endpoint
The endpoint is the URL where your service can be accessed by a client application. To see the WSDL you add
?wsdl
to the web service endpoint URL.
Let's create a simple hello world webservice.
Content of
server.php
: <?php
require_once __DIR__ . '/vendor/autoload.php';
class Hello
{
/**
* Say hello.
*
* @param string $firstName
* @return string $greetings
*/
public function sayHello($firstName)
{
return 'Hello ' . $firstName;
}
}
$serverUrl = "http://localhost/hello/server.php";
$options = [
'uri' => $serverUrl,
];
$server = new Zend\Soap\Server(null, $options);
if (isset($_GET['wsdl'])) {
$soapAutoDiscover = new \Zend\Soap\AutoDiscover(new \Zend\Soap\Wsdl\ComplexTypeStrategy\ArrayOfTypeSequence());
$soapAutoDiscover->setBindingStyle(array('style' => 'document'));
$soapAutoDiscover->setOperationBodyStyle(array('use' => 'literal'));
$soapAutoDiscover->setClass('Hello');
$soapAutoDiscover->setUri($serverUrl);
header("Content-Type: text/xml");
echo $soapAutoDiscover->generate()->toXml();
} else {
$soap = new \Zend\Soap\Server($serverUrl . '?wsdl');
$soap->setObject(new \Zend\Soap\Server\DocumentLiteralWrapper(new Hello()));
$soap->handle();
}
Creating a SOAP Client
Create a new file
client.php
.
File content:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$client = new Zend\Soap\Client('http://localhost/hello/server.php?wsdl');
$result = $client->sayHello(['firstName' => 'World']);
echo $result->sayHelloResult;
The result (response) should look like this:
Hello World
It is possible that your PHP Static Analysis Tool (e.g. phpstan) has a problem with calling
$client->sayHello(...)
. The reason is that this method does not exist and is called internally via a magic method. To avoid this warning there is a simple trick. Instead, call the web service methods using call(method, params)
-methode and simply pass the method name as a string. Note that the parameters must be passed in a double nested array.
$result = $client->call('sayHello', [['firstName' => 'World']]);
echo $result->sayHelloResult;
fuente:
https://dev.to/dopitz/implementing-a-soap-api-with-php-a3n
nota:
si despues de una primera ejecucion se quiere agregar nuevos metodos, o modificar el existente y que lo reconozca el client, se debe agregar tanto en el server como el client
la sgt linea (despues del require...) para que no lea la caché, sino no va a encontrar los nuevos metodos
ini_set('soap.wsdl_cache_enabled', '0');
No hay comentarios:
Publicar un comentario