How to use Attachment Caching with WSF/PHP

Monday, October 20, 2008

WSF/PHP 2.0.0 has the support for caching attachments ( writing to a file ). This effectively reduces the amount of memory used when sending and receiving attachments and its specially useful, if your application requires to send or receiving a very large file in the scale of megabytes.

WSF/PHP adds two php.ini entries in order to allow attachment caching.

1. wsf.attachment_cache_dir

2.wsf.enable_attachment_caching

wsf.attachment_cache dir is the location where the received attachments will be saved.

wsf.enable_attachment_caching option enables attachment caching.

By default, attachment caching can be done only for attachments larger than 1 MB.

Lets see a code sample on how to use this. This is a simple php service, which reads a binary file and send it to the client as an  MTOM attachment.

<?php

ini_set("wsf.enable_attachment_caching", 1);
ini_set("wsf.attachment_cache_dir","E:\\");

function sendAttachment($msg)
{
$responsePayloadString = <<<XML
        <ns1:download xmlns:ns1="http://php.axis2.org/samples/mtom">
            <ns1:fileName>test.jpg</ns1:fileName>
                <ns1:image xmlmime:contentType="image/jpeg" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
                    <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:myid1"></xop:Include>
                </ns1:image>
        </ns1:download>
XML;
                                       

    $responseMessage = new WSMessage($responsePayloadString,
            array( "attachments" => array("myid1" => "../resources/large_image.jpg"))); 
    return $responseMessage;   
}

$operations = array("download" => "sendAttachment");

$service = new WSService(array("operations" => $operations, "useMTOM" => TRUE));

$service->reply();

?>

Now in above code, I have highlighted the important code pieces.

1. The php ini settings at the top of the code where the attachment_cache_dir is set and attachment caching is enabled.

ini_set("wsf.enable_attachment_caching", 1);
ini_set("wsf.attachment_cache_dir","E:\\");

2. Setting of a fake content id to which the actual attachment is assigned.

href="cid:myid1"

3. Instead of setting binary attachment as an string in the attachment array, we should set the actual path to the file.

array("myid1" => "../resources/large_image.jpg")

Thats all you need to do to get attachment caching working. The same technique can be used for the client as well. It will be consuming lot less amount of memory.

No comments: