开发者

Consuming a webservice code simplification

UPDATED CODE TO LATEST ITERATION

The following function consumes a webservice that returns address details based on zip code (CEP). I'm using this function to parse the xml and populate an empty query with the address details. I would like to know if there is a more elegant way to achieve the same result. It seems to be a waste to create an empty query and populate it...

Any ideas could my method be modified or the code factored/simplified?

<!--- ****** ACTION: getAddress (consumes web-service to retrieve address details) --->
<cffunction name="getAddress" access="remote" returntype="any" output="false">

    <!--- Defaults: strcep (cep (Brazilian zip-code) string webservice would look for), search result returned from webservice --->
    <cfargument name="cep" type="string" default="00000000">
    <cfset var searchResult = "">
    <cfset var nodes = "">
    <cfset var cfhttp = "">
    <cfset var stateid = 0>
    <cfset var tmp = structNew()>

    <!--- Validate cep string --->
    <cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>

        <cftry>

            <!--- Consume webservice --->                
            <cfhttp method开发者_如何学Python="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#"></cfhttp>
            <cfset searchResult = xmlparse(cfhttp.FileContent)>
            <cfset nodes = xmlSearch(searchResult, "//tbCEP")>

            <!--- If result insert address data into session struct --->
            <cfif arrayLen(nodes)>

                <cfset tmp.streetType = nodes[1].logradouro.XmlText>
                <cfset tmp.streetName = nodes[1].nome.XmlText>
                <cfset tmp.area = nodes[1].bairro.XmlText>
                <cfset tmp.city = nodes[1].cidade.XmlText>
                <cfset tmp.state = nodes[1].uf.XmlText>
                <cfset tmp.cep = arguments.cep>

                <!--- Get state id and add to struct --->
                <cfset stateid = model("state").findOneByStateInitials(tmp.state)>
                <cfset tmp.stateid = stateid.id>

                <cfreturn tmp>

            </cfif>

            <!--- Display error if any --->
            <cfcatch type="any">
                <cfoutput>
                    <h3>Sorry, but there was an error.</h3>
                    <p>#cfcatch.message#</p>
                </cfoutput>
            </cfcatch>

        </cftry>

    </cfif>

</cffunction>
<!--- ****** END ACTION getAddress --->

The calling code:

        <!--- Get address data based on CEP --->
        <cfset session.addressData = getAddress(cep=params.newMember.cep)>


I can't test this because I don't have an example XML file / CEP to test with, but here is a minor rewrite that addresses four things:

  • Instead of using cfparam and some strange "params" structure, you should pass the CEP into the function as an argument.
  • The function shouldn't directly modify session data. Instead, you should return the result and let the calling code assign it to the session (or wherever else it might be needed). I'll show this in a 2nd code example.
  • Cache the xml result per CEP -- assuming this doesn't change often. (You'll have to improve it further if you want time-based manual cache invalidation, but I can help add that if necessary)
  • Don't use StructInsert. It's not necessary and you're just writing it the long way for the sake of writing it the long way. There is no benefit.

Again, this isn't tested, but hopefully it's helpful:

<cffunction name="getAddress" access="remote" returntype="any" output="false">
    <cfargument name="cep" type="string" default="00000000" /><!--- (cep (Brazilian zip-code) string webservice would look for) --->
    <cfset var searchResult = "">
    <cfset var nodes = "">
    <cfset var cfhttp = "">
    <cfset var stateid = 0 />
    <cfset var tmp = structNew()>

    <!--- Validate cep string --->
    <cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>

        <cfif not structKeyExists(application.cepCache, arguments.cep)><!--- or cache is expired: you'd have to figure this part out --->

            <!--- Consume webservice --->
            <cftry>
                <cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#" />
                <cfset searchResult = xmlparse(cfhttp.FileContent)>
                <cfset nodes = xmlSearch(searchResult, "//tbCEP")>

                <!--- If result insert address data into session struct --->
                <cfif arrayLen(nodes)>

                    <cfset tmp.streetType = nodes[1].logradouro.XmlText />
                    <cfset tmp.streetName = nodes[1].nome.XmlText />
                    <cfset tmp.area = nodes[1].bairro.XmlText />
                    <cfset tmp.city = nodes[1].cidade.XmlText />
                    <cfset tmp.state = nodes[1].uf.XmlText />
                    <cfset tmp.cep = arguments.cep />

                    <!--- Get state id and add to struct --->
                    <cfset stateid = model("state").findOneByStateInitials(session.addressData.state)>
                    <cfset tmp.stateid = stateid.id />

                </cfif>

                <cfreturn duplicate(tmp) />

                <!--- Display error if any --->
                <cfcatch type="any">
                    <h3>Sorry, but there was an error.</h3>
                    <p>#cfcatch.message#</p>
                </cfcatch>

            </cftry>

        <cfelse>

            <!--- cache exists and is not expired, so use it --->
            <cfreturn duplicate(application.cepCache[arguments.cep]) />

        </cfif>

    </cfif>
<!---
    <!--- Redirect to page two of the sign up process --->
    <cfset redirectTo(controller="assine", action="perfil")>
--->

</cffunction>

Notice that I commented out the redirect you had at the end. That's because with my function, you'll be returning a value, and the redirect should be done after that, like so:

<cfset session.addressData = getAddress("some-CEP-value") />
<cfset redirectTo(controller="assine", action="perfil")>

If you're going to leave out the caching (As you say in a comment you will), then here is a version that makes no attempt at caching:

<cffunction name="getAddress" access="remote" returntype="any" output="false">
    <cfargument name="cep" type="string" default="00000000" /><!--- (cep (Brazilian zip-code) string webservice would look for) --->
    <cfset var searchResult = "">
    <cfset var nodes = "">
    <cfset var cfhttp = "">
    <cfset var stateid = 0 />
    <cfset var tmp = structNew()>

    <!--- Validate cep string --->
    <cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>

        <!--- Consume webservice --->
        <cftry>
            <cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#" />
            <cfset searchResult = xmlparse(cfhttp.FileContent)>
            <cfset nodes = xmlSearch(searchResult, "//tbCEP")>

            <!--- If result insert address data into session struct --->
            <cfif arrayLen(nodes)>

                <cfset tmp.streetType = nodes[1].logradouro.XmlText />
                <cfset tmp.streetName = nodes[1].nome.XmlText />
                <cfset tmp.area = nodes[1].bairro.XmlText />
                <cfset tmp.city = nodes[1].cidade.XmlText />
                <cfset tmp.state = nodes[1].uf.XmlText />
                <cfset tmp.cep = arguments.cep />

                <!--- Get state id and add to struct --->
                <cfset stateid = model("state").findOneByStateInitials(session.addressData.state)>
                <cfset tmp.stateid = stateid.id />

            </cfif>

            <cfreturn duplicate(tmp) />

            <!--- Display error if any --->
            <cfcatch type="any">
                <h3>Sorry, but there was an error.</h3>
                <p>#cfcatch.message#</p>
            </cfcatch>

        </cftry>

    </cfif>

<!---
    <!--- Redirect to page two of the sign up process --->
    <cfset redirectTo(controller="assine", action="perfil")>
--->

</cffunction>

Note that I did leave in the use of duplicate(). What this does is return a duplicate of the object (in this case, the struct). This is much more important when you start to work on applications where you're passing complex values into and out of functions over and over again. Using duplicate() causes things to be passed by value instead of by reference. It may not bite you in this case, but it's a good habit to get into.

I would also still use the function argument and return a value -- but it's arguable that this is my personal preference. In a way it is. I believe that a function should be fully encapsulated; a total "black box". You give it some input and it gives you back some output. It should not modify anything outside of itself. (Again, just my opinion.)

So assuming you're using this function as part of a larger multi-step process, you should still use it the same way I've described above. The only difference is that you're setting the session variable outside of the function body. Just as previously:

<cfset session.addressData = getAddress("some-CEP-value") />
<cfset redirectTo(controller="assine", action="perfil")>


That looks pretty straightforward. CF doesn't (yet?) have any magical XML-to-Query functions, but that would be pretty cool. If you wanted, you could probably write up an XSL transform to go from XML to WDDX so that you could use the cfwddx tag ... but that's probably putting the cart before the horse.

You need to move your arrayLen() if block into the try block. As it stands, if the cfhttp tag throws an error, the nodes variable will be a string and not an array, thus causing the arrayLen() to throw another error.

Minor nitpick: I wouldn't add a row to the query until inside the arrayLen() block. That way, the calling code can check recordCount to see if the result was a success.

Beyond that ... that's pretty much how it's done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜