Magento API and C# – Part I Extended – AND/OR Filters

I already identified some of the shortcomings of the Magento SOAP API in my previous article including a lack of pagination. Since then I’ve realised another interesting feature that I think is missing (or at least I can’t seem to find) and that is the ability to do an OR query via the API. By default, Magento treats all filters as AND queries. For example if I want to search for myself amongst the customers I could use the following filter:

AND query

PHP

1

2

3

4

$filters=array('filter'=>array(

array('key'=>'firstname','value'=>'Jarrod'),

array('key'=>'lastname','value'=>'Demeza')

));

Which would create a SQL where clause like this:

AND where clause

Transact-SQL

1

WHEREfirstname='Jarrod'ANDlastname='Demeza'

But what if I wanted to find myself or a different customer? How do we construct our filter? To answer that question we are going to further enhance our module by creating a data helper that allows for a combination of AND and OR queries.

Create the helper

Helpers are stored in the Helper directory. Create that directory and the following file:
app/code/local/MezaIT/CustomerAddress/Helper/Data.php

Customer Address Helper

PHP

1

2

3

4

<?php

classMezaIT_CustomerAddress_Helper_DataextendsMage_Api_Helper_Data{

...

}

Notice our class extends the Mage_Api_Helper_Data class. For the full implementation refer to the code on Github.

Update the configuration

The same way we told the module about our models in the previous article, we need let the module know about the new helper. Add this entry to the config.xml in the ‘global’ section.

Helpers XML definition

XHTML

1

2

3

4

5

<helpers>

<mezait_customeraddress>

<class>MezaIT_CustomerAddress_Helper</class>

</mezait_customeraddress>

</helpers>

Putting it to use

We can now call the helper from our API code like this:

Putting it to use

PHP

1

2

$helper=Mage::helper('mezait_customeraddress');

$parsedFilters=$helper->parseFilters($filters);

For a better example take a look on Github where I have updated our existing ‘count’ and ‘pagedList’ methods to use the new helper.

Wrap Up

Before we made our changes, filters where simply an array of complex filters that were interpreted as an AND query by Magento. Our helper has extended our methods to expect an array of arrays of complex filters. The inner arrays are the AND queries and the outer array is the OR query.