coldfusion component (CFC) 另一種用法


一般 CFC 的寫法大概會像上面這樣:

而呼叫方式如下:


<cfinvoke component="COM.extfunc" method="myescape" returnvariable="escstr">
    <cfinvokeargument name="sdata" value="#myForm.note#">
</cfinvoke>

<!--- 返回 escstr --->
<cfoutput>#escstr#</cfoutput>


上面這種方式屬於純 TAG 寫法,寫起來超麻煩,尤其參數很多時就會寫出一堆  <cfinvokeargument>,真是快昏倒了。

其實,也可以使用創建物件方式來使用這個 Component,會方便許多。

我們把上面的 cfc 改成下面方式


<cfcomponent displayname="extfunc" hint="擴充功能">



     <cffunction name="Init" access="public" returntype="QueryUtility" output="false"
          hint="Returns an initialized QueryUtility instance.">

          <!--- Return This reference. --->
          <cfreturn THIS />
     </cffunction>


     <cffunction name="myescape" access="public" returntype="string" hint="跳脫字元處理"
     description="轉換要顯示在HTML上的特殊字元,這是CF用的,若使用AJAX請使用jquery-extend.js裡面的myescape">
   
          <cfargument name="sdata" type="string" required="yes" hint="來源字串">
     
          <cfset Escaped=Replace(sdata,"<","&lt;","All")>
        <cfset Escaped=Replace(Escaped,">","&gt;","All")>
        <cfset Escaped=Replace(Escaped,"'","""","All")>
        <!---由於是CFOUTPUT使用所以要加上#字處理--->
        <cfset Escaped=Replace(Escaped,"##","####","All")>

        <cfreturn Escaped>
     
     </cffunction>
 
</cfcomponent>


增加了 Init 這個函式,裡用此函式將物件傳回使用。

使用方式就會變成下面方式


<cfset extf = CreateObject("component","COM.extfunc").Init() >

<cfset escstr = extf .myescape(myForm.note) >

<cfoutput>#escstr#</cfoutput>


使用起來真的直覺多了,也方便閱讀,至少不用寫一堆 <cfinvokeargument>



留言

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式