Writing Soap Requests In Magento Done Right

Every Magento implementation I have had the privilege to work on has at some point leveraged a third party’s API. Every API has its specific oddities, whether its a funky XSD, WSDL, json API, SOAP, REST, Socket, Queue, AMF, etc…

PHP has some very powerful built in methods of handling request coding. The stdClass() is a great way to build requests in a very developer readable format and can easily be converted to a SoapClient request a json string, a POST array, and a few other API compatible formats…

$request = new stdClass();
$request->username = "username";
$request->api_key = "783f6t78wrqetgfuvywergvf38749fyhi3";
$request->items_ordered = array();
* Now suppose you needed to send information about each item in an order
foreach( $order->getItems() as $item){
    $items = new stdClass();
    $items->product_name = $item->getName();
    $items->price = $item->getPrice();
    $request->items_ordered[] = $items;
//Lets look at how we'd turn this request into a json string
$jsonRequest = json_encode($request);
//Lets look at how we'd turn this request into a SoapClient request
$client = new SoapClient($wsdl, array('trace' => $trace));
$response = $client->someWsdlFunction( $request );
//There's often more involved with a SOAP call, but this covers the basics of building a SOAP request.

Thats all there is to it. The hierarchical nesting found in most of the exposed APIs that Magento is often integrated with are easily coded, readable, and parsable into the request call with the simple PHP stdClass()!