Using the PHP Soap Extension to create a Web Service in a Symfony2 Controller
on July 1st, 2011 at 3:40 pmI struggled for awhile to find a way to create a Web Service in an SF2 Controller. The problem I had with NuSOAP was it’s ability to only call static methods and the obscure syntax it forced on the method names on the client side.
There is also a “WebServiceBundle” that is broken in the current release of SF2 (RC3) on symfony2bundles and I, having not hacked around with SF2′s annotation system, was not in a position to fix.
I ended up using PHP’s SOAP Extension and things worked beautifully and simply. The only drawback is that, from what I can tell, PHP SOAP will not generate a WSDL for you. I just made a dummy nusoap_server and registered a method ‘hello’ with it an let nusoap generate a WSDL that I used whole-sale for this example.
class XmlPostServiceController extends Controller {
public function indexAction() {
$server = new \SoapServer('/path/to/hello.wsdl');
$server->setObject($this);
$response = new Response();
$response->headers->set('Content-Type', 'text/xml; charset=ISO-8859-1');
ob_start();
$server->handle();
$response->setContent(ob_get_contents());
ob_clean();
return $response;
}
public function hello($name) {
$em = $this->get('doctrine')->getEntityManager();
$user = $em->createQuery('SELECT u FROM Entity:Users u WHERE u.username = :uname')->setParameter('uname', $name)->getSingleResult();
return 'Hello, ' . $name . '! Your user_id is ' . $user->getUserId() . '.';
}
}
You may have noticed the “ob_start”, “ob_get_contents”, and “ob_clean” function calls. The “service” method of SoapServer echos it’s output, but we need to return a Response object. These “ob_” functions are for “output buffering”. After ob_start(), all echoed messages are trapped in the output buffer, which we dump in as the “content” of our Response.
You also want to be sure to set the “Content-Type” header of the response to “text/xml” as that is what the client will expect.
Below is a client-side example using nusoap (replace URL with our URL and route).
$client = new nusoap_client('http://example.com/app.php/webservice?wsdl', true);
$result = $client->call('hello', array('name' => 'World'));
Hope this helps.
Roger