Zend_Amf-Server.xml 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.amf.server">
  4. <title>Zend_Amf_Server</title>
  5. <para>
  6. <classname>Zend_Amf_Server</classname> provides an RPC-style server for handling
  7. requests made from the Adobe Flash Player using the AMF protocol. Like
  8. all Zend Framework server classes, it follows the SoapServer API,
  9. providing an easy to remember interface for creating servers.
  10. </para>
  11. <example id="zend.amf.server.basic">
  12. <title>Basic AMF Server</title>
  13. <para>
  14. Let's assume that you have created a class <code>Foo</code> with a
  15. variety of public methods. You may create an AMF server using the
  16. following code:
  17. </para>
  18. <programlisting role="php"><![CDATA[
  19. $server = new Zend_Amf_Server();
  20. $server->setClass('Foo');
  21. $response = $server->handle();
  22. echo $response;
  23. ]]></programlisting>
  24. <para>
  25. Alternately, you may choose to attach a simple function as a
  26. callback instead:
  27. </para>
  28. <programlisting role="php"><![CDATA[
  29. $server = new Zend_Amf_Server();
  30. $server->addFunction('myUberCoolFunction');
  31. $response = $server->handle();
  32. echo $response;
  33. ]]></programlisting>
  34. <para>
  35. You could also mix and match multiple classes and functions. When
  36. doing so, we suggest namespacing each to ensure that no method name
  37. collisions occur; this can be done by simply passing a second string
  38. argument to either <code>addFunction()</code> or
  39. <code>setClass()</code>:
  40. </para>
  41. <programlisting role="php"><![CDATA[
  42. $server = new Zend_Amf_Server();
  43. $server->addFunction('myUberCoolFunction', 'my')
  44. ->setClass('Foo', 'foo')
  45. ->setClass('Bar', 'bar');
  46. $response = $server->handle();
  47. echo $response;
  48. ]]></programlisting>
  49. <para>
  50. The <code>Zend Amf Server</code> also allows services to be dynamically loaded
  51. based on a supplied directory path. You may add as many directories as you wish
  52. to the server. The order that you add the directories to the server will be the
  53. order that the LIFO search will be performed on the directories to match the class.
  54. Adding directories is completed with the <code>addDirectory()</code> method.
  55. </para>
  56. <programlisting role="php"><![CDATA[
  57. $server->addDirectory(dirname(__FILE__) .'/../services/');
  58. $server->addDirectory(dirname(__FILE__) .'/../package/');
  59. ]]></programlisting>
  60. <para>
  61. When calling remote services your source name can have underscore(_) and dot(.)
  62. directory delimiters. When an underscore is used PEAR and Zend Framework class naming
  63. conventions will be respected. This means that if you call the service
  64. <code>com_Foo_Bar</code> the server will look for the file Bar.php in the each of the
  65. included paths at <code>com/Foo/Bar.php</code>. If the dot notation is used for your
  66. remote service such as <code>com.Foo.Bar</code> each included path will have
  67. <code>com/Foo/Bar.php</code> append to the end to autoload Bar.php
  68. </para>
  69. <para>
  70. All AMF requests sent to the script will then be handled by the
  71. server, and an AMF response will be returned.
  72. </para>
  73. </example>
  74. <note>
  75. <title>All Attached Methods and Functions Need Docblocks</title>
  76. <para>
  77. Like all other server components in Zend Framework, you must
  78. document your class methods using PHP docblocks. At the minimum, you
  79. need to provide annotations for each required argument as well as
  80. the return value. As examples:
  81. </para>
  82. <programlisting role="php"><![CDATA[
  83. // Function to attach:
  84. /**
  85. * @param string $name
  86. * @param string $greeting
  87. * @return string
  88. */
  89. function helloWorld($name, $greeting = 'Hello')
  90. {
  91. return $greeting . ', ' . $name;
  92. }
  93. ]]></programlisting>
  94. <programlisting role="php"><![CDATA[
  95. // Attached class
  96. class World
  97. {
  98. /**
  99. * @param string $name
  100. * @param string $greeting
  101. * @return string
  102. */
  103. public function hello($name, $greeting = 'Hello')
  104. {
  105. return $greeting . ', ' . $name;
  106. }
  107. }
  108. ]]></programlisting>
  109. <para>
  110. Other annotations may be used, but will be ignored.
  111. </para>
  112. </note>
  113. <sect2 id="zend.amf.server.flex">
  114. <title>Connecting to the Server from Flex</title>
  115. <para>
  116. Connecting to your <classname>Zend_Amf_Server</classname> from your Flex
  117. project is quite simple; you simply need to point your endpoint URI
  118. to your <classname>Zend_Amf_Server</classname> script.
  119. </para>
  120. <para>
  121. Say, for instance, you have created your server and placed it in the
  122. <code>server.php</code> file in your application root, and thus the
  123. URI is <code>http://example.com/server.php</code>. In this case, you
  124. would modify your services-config.xml file to set the channel
  125. endpoint uri attribute to this value.
  126. </para>
  127. <para>
  128. If you have never created a service-config.xml file you can do so by opening your
  129. project in your Navigator window. Right click on the project name and select
  130. ‘properties’. In the Project properties dialog go into ‘Flex Build Path’ menu,
  131. ‘Library path’ tab and be sure the ‘rpc.swc’ file is added to your projects path
  132. and Press Ok to close the window.
  133. </para>
  134. <para>
  135. You will also need to tell the compiler to use the service-config.xml to find
  136. the RemoteObject endpoint. To do this open your project properties panel again by
  137. right clicking on the project folder from your Navigator and selecting properties.
  138. From the properties popup select ‘Flex Compiler’ and add the
  139. string: -services “services-config.xml”. Press Apply then OK to return to update
  140. the option. What you have just done is told the Flex compiler to look to the
  141. services-config.xml file for runtime variables that will be used by the
  142. RemotingObject class.
  143. </para>
  144. <para>
  145. We now need to tell Flex which services configuration file to use for connecting to
  146. our remote methods. For this reason create a new ‘services-config.xml’ file into your
  147. Flex project src folder. To do this right click on the project folder and select
  148. ‘new’ ‘File’ which will popup a new window. Select the project folder and then name
  149. the file ‘services-config.xml’ and press finish.
  150. </para>
  151. <para>
  152. Flex has created the new services-config.xml and has it open. Use the following example
  153. text for your services-config.xml file. Make sure that you update your endpoint to
  154. match that of your testing server. Make sure you save the file.
  155. </para>
  156. <programlisting role="xml"><![CDATA[
  157. <?xml version="1.0" encoding="UTF-8"?>
  158. <services-config>
  159. <services>
  160. <service id="zend-service"
  161. class="flex.messaging.services.RemotingService"
  162. messageTypes="flex.messaging.messages.RemotingMessage">
  163. <destination id="zend">
  164. <channels>
  165. <channel ref="zend-endpoint"/>
  166. </channels>
  167. <properties>
  168. <source>*</source>
  169. </properties>
  170. </destination>
  171. </service>
  172. </services>
  173. <channels>
  174. <channel-definition id="zend-endpoint"
  175. class="mx.messaging.channels.AMFChannel">
  176. <endpoint uri="http://example.com/server.php"
  177. class="flex.messaging.endpoints.AMFEndpoint"/>
  178. </channel-definition>
  179. </channels>
  180. </services-config>
  181. ]]></programlisting>
  182. <para>
  183. There are two key points in the example. First, but last in the
  184. listing, we create an AMF channel, and specify the endpoint as the
  185. URL to our <classname>Zend_Amf_Server</classname>:
  186. </para>
  187. <programlisting role="xml"><![CDATA[
  188. <channel-definition id="zend-endpoint"
  189. <endpoint uri="http://example.com/server.php"
  190. class="flex.messaging.endpoints.AMFEndpoint"/>
  191. </channel-definition>
  192. ]]></programlisting>
  193. <para>
  194. Notice that we've given this channel an identifier, "zend-endpoint".
  195. The example create a service destination that refers to this channel,
  196. assigning it an ID as well -- in this case "zend".
  197. </para>
  198. <para>
  199. Within our Flex MXML files, we need to bind a RemoteObject to the
  200. service. In MXML, this might be done as follows:
  201. </para>
  202. <programlisting role="xml"><![CDATA[
  203. <mx:RemoteObject id="myservice"
  204. fault="faultHandler(event)"
  205. showBusyCursor="true"
  206. destination="zend">
  207. ]]></programlisting>
  208. <para>
  209. Here, we've defined a new remote object identified by "myservice"
  210. bound to the service destination "zend" we defined in the
  211. <code>services-config.xml</code> file. We then call methods on it in
  212. in our ActionScript by simply calling "myservice.&lt;method&gt;".
  213. As an example:
  214. </para>
  215. <programlisting role="ActionScript"><![CDATA[
  216. myservice.hello("Wade");
  217. ]]></programlisting>
  218. <para>
  219. When namespacing, you would use
  220. "myservice.&lt;namespace&gt;.&lt;method&gt;":
  221. </para>
  222. <programlisting role="ActionScript"><![CDATA[
  223. myservice.world.hello("Wade");
  224. ]]></programlisting>
  225. <para>
  226. For more information on Flex RemoteObject invocation, <ulink
  227. url="http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_4.html">
  228. visit the Adobe Flex 3 Help site</ulink>.
  229. </para>
  230. </sect2>
  231. <sect2 id="zend.amf.server.errors">
  232. <title>Error Handling</title>
  233. <para>
  234. By default, all exceptions thrown in your attached classes or
  235. functions will be caught and returned as AMF ErrorMessages. However,
  236. the content of these ErrorMessage objects will vary based on whether
  237. or not the server is in "production" mode (the default state).
  238. </para>
  239. <para>
  240. When in production mode, only the exception code will be returned.
  241. If you disable production mode -- something that should be done for
  242. testing only -- most exception details will be returned: the
  243. exception message, line, and backtrace will all be attached.
  244. </para>
  245. <para>
  246. To disable production mode, do the following:
  247. </para>
  248. <programlisting role="php"><![CDATA[
  249. $server->setProduction(false);
  250. ]]></programlisting>
  251. <para>
  252. To re-enable it, pass a true boolean value instead:
  253. </para>
  254. <programlisting role="php"><![CDATA[
  255. $server->setProduction(true);
  256. ]]></programlisting>
  257. <note>
  258. <title>Disable production mode sparingly!</title>
  259. <para>
  260. We recommend disabling production mode only when in development.
  261. Exception messages and backtraces can contain sensitive system
  262. information that you may not wish for outside parties to access.
  263. Even though AMF is a binary format, the specification is now
  264. open, meaning anybody can potentially deserialize the payload.
  265. </para>
  266. </note>
  267. <para>
  268. One area to be especially careful with is PHP errors themselves.
  269. When the <code>display_errors</code> INI directive is enabled, any
  270. PHP errors for the current error reporting level are rendered
  271. directly in the output -- potentially disrupting the AMF response
  272. payload. We suggest turning off the <code>display_errors</code>
  273. directive in production to prevent such problems
  274. </para>
  275. </sect2>
  276. <sect2 id="zend.amf.server.response">
  277. <title>AMF Responses</title>
  278. <para>
  279. Occasionally you may desire to manipulate the response object
  280. slightly, typically to return extra message headers. The
  281. <code>handle()</code> method of the server returns the response
  282. object, allowing you to do so.
  283. </para>
  284. <example id="zend.amf.server.response.messageHeaderExample">
  285. <title>Adding Message Headers to the AMF Response</title>
  286. <para>
  287. In this example, we add a 'foo' MessageHeader with the value
  288. 'bar' to the response prior to returning it.
  289. </para>
  290. <programlisting role="php"><![CDATA[
  291. $response = $server->handle();
  292. $response->addAmfHeader(new Zend_Amf_Value_MessageHeader('foo', true, 'bar'))
  293. echo $response;
  294. ]]></programlisting>
  295. </example>
  296. </sect2>
  297. <sect2 id="zend.amf.server.typedobjects">
  298. <title>Typed Objects</title>
  299. <para>
  300. Similar to SOAP, AMF allows passing objects between the client and
  301. server. This allows a great amount of flexibility and coherence
  302. between the two environments.
  303. </para>
  304. <para>
  305. <classname>Zend_Amf</classname> provides three methods for mapping
  306. ActionScript and PHP objects.
  307. </para>
  308. <itemizedlist>
  309. <listitem>
  310. <para>
  311. First, you may create explicit bindings at the server level,
  312. using the <code>setClassMap()</code> method. The first
  313. argument is the ActionScript class name, the second the PHP
  314. class name it maps to:
  315. </para>
  316. <programlisting role="php"><![CDATA[
  317. // Map the ActionScript class 'ContactVO' to the PHP class 'Contact':
  318. $server->setClassMap('ContactVO', 'Contact');
  319. ]]></programlisting>
  320. </listitem>
  321. <listitem>
  322. <para>
  323. Second, you can set the public property
  324. <code>$_explicitType</code> in your PHP class, with the
  325. value representing the ActionScript class to map to:
  326. </para>
  327. <programlisting role="php"><![CDATA[
  328. class Contact
  329. {
  330. public $_explicitType = 'ContactVO';
  331. }
  332. ]]></programlisting>
  333. </listitem>
  334. <listitem>
  335. <para>
  336. Third, in a similar vein, you may define the public method
  337. <code>getASClassName()</code> in your PHP class; this method
  338. should return the appropriate ActionScript class:
  339. </para>
  340. <programlisting role="php"><![CDATA[
  341. class Contact
  342. {
  343. public function getASClassName()
  344. {
  345. return 'ContactVO';
  346. }
  347. }
  348. ]]></programlisting>
  349. </listitem>
  350. </itemizedlist>
  351. <para>
  352. Although we have created the ContactVO on the server we now need to make
  353. its corresponding class in AS3 for the server object to be mapped to.
  354. </para>
  355. <para>
  356. Right click on the src folder of the Flex project and select New -> ActionScript
  357. File. Name the file ContactVO and press finish to see the new file. Copy the
  358. following code into the file to finish creating the class.
  359. </para>
  360. <programlisting role="as"><![CDATA[
  361. package
  362. {
  363. [Bindable]
  364. [RemoteClass(alias="ContactVO")]
  365. public class ContactVO
  366. {
  367. public var id:int;
  368. public var firstname:String;
  369. public var lastname:String;
  370. public var email:String;
  371. public var mobile:String;
  372. public function ProductVO():void {
  373. }
  374. }
  375. }
  376. ]]></programlisting>
  377. <para>
  378. The class is syntactically equivalent to the PHP of the same name.
  379. The variable names are exactly the same and need to be in the same case
  380. to work properly. There are two unique AS3 meta tags in this class.
  381. The first is bindable which makes fire a change event when it is updated.
  382. The second tag is the RemoteClass tag which defines that this class can
  383. have a a remote object mapped with the alias name in this case <code>ContactVO</code>
  384. It is mandatory that this tag the value that was set is the PHP class are strictly
  385. equivalent.
  386. </para>
  387. <programlisting role="as"><![CDATA[
  388. [Bindable]
  389. private var myContact:ContactVO;
  390. private function getContactHandler(event:ResultEvent):void {
  391. myContact = ContactVO(event.result);
  392. }
  393. ]]></programlisting>
  394. <para>
  395. The following result event from the service call is cast instantly onto the Flex
  396. ContactVO. Anything that is bound to myContact will be updated with the returned
  397. ContactVO data.
  398. </para>
  399. </sect2>
  400. <sect2 id="zend.amf.server.flash">
  401. <title>Connecting to the Server from Flash</title>
  402. <para>
  403. Connecting to your <classname>Zend_Amf_Server</classname> from your Flash project is
  404. slightly different than from Flex. However once the connection Flash functions with
  405. <classname>Zend_Amf_Server</classname> the same way is flex. The following example can
  406. also be used from a Flex AS3 file. We will reuse the same
  407. <classname>Zend_Amf_Server</classname> configuration along with the World class for our
  408. connection.
  409. </para>
  410. <para>
  411. Open Flash CS and create and new Flash File (ActionScript 3). Name the document
  412. ZendExample.fla and save the document into a folder that you will use for this example.
  413. Create a new AS3 file in the same directory and call the file Main.as. Have both files
  414. open in your editor. We are now going to connect the two files via the document class.
  415. Select ZendExample and click on the stage. From the stage properties panel change the
  416. Document class to Main. This links the Main.as ActionScript file with the user
  417. interface in ZendExample.fla. When you run the Flash file ZendExample the Main.as class
  418. will now be run. Next we will add ActionScript to make the AMF call.
  419. </para>
  420. <para>
  421. We now are going to make a Main class so that we can send the data to the server and
  422. display the result. Copy the following code into your Main.as file and then we will
  423. walk through the code to describe what each element's role is.
  424. </para>
  425. <programlisting role="as"><![CDATA[
  426. package {
  427. import flash.display.MovieClip;
  428. import flash.events.*;
  429. import flash.net.NetConnection;
  430. import flash.net.Responder;
  431. public class Main extends MovieClip {
  432. private var gateway:String = "http://example.com/server.php";
  433. private var connection:NetConnection;
  434. private var responder:Responder;
  435. public function Main() {
  436. responder = new Responder(onResult, onFault);
  437. connection = new NetConnection;
  438. connection.connect(gateway);
  439. }
  440. public function onComplete( e:Event ):void{
  441. var params = "Sent to Server";
  442. connection.call("World.hello", responder, params);
  443. }
  444. private function onResult(result:Object):void {
  445. // Display the returned data
  446. trace(String(result));
  447. }
  448. private function onFault(fault:Object):void {
  449. trace(String(fault.description));
  450. }
  451. }
  452. }
  453. ]]></programlisting>
  454. <para>
  455. We first need to import two ActionScript libraries that perform the bulk of the work.
  456. The first is NetConnection which acts like a by directional pipe between the client and
  457. the server. The second is a Responder object which handles the return values from the
  458. server related to the success or failure of the call.
  459. </para>
  460. <programlisting role="as"><![CDATA[
  461. import flash.net.NetConnection;
  462. import flash.net.Responder;
  463. ]]></programlisting>
  464. <para>
  465. In the class we need three variables to represent the NetConnection, Responder, and
  466. the gateway URL to our <classname>Zend_Amf_Server</classname> installation.
  467. </para>
  468. <programlisting role="as"><![CDATA[
  469. private var gateway:String = "http://example.com/server.php";
  470. private var connection:NetConnection;
  471. private var responder:Responder;
  472. ]]></programlisting>
  473. <para>
  474. In the Main constructor we create a responder and a new connection to the
  475. <classname>Zend_Amf_Server</classname> endpoint. The responder defines two different
  476. methods for handling the response from the server. For simplicity I have called these
  477. onResult and onFault.
  478. </para>
  479. <programlisting role="as"><![CDATA[
  480. responder = new Responder(onResult, onFault);
  481. connection = new NetConnection;
  482. connection.connect(gateway);
  483. ]]></programlisting>
  484. <para>
  485. In the onComplete function which is run as soon as the construct has completed we send
  486. the data to the server. We need to add one more line that makes a call to the
  487. <classname>Zend_Amf_Server</classname> World->hello function.
  488. </para>
  489. <programlisting role="as"><![CDATA[
  490. connection.call("World.hello", responder, params);
  491. ]]></programlisting>
  492. <para>
  493. When we created the responder variable we defined an onResult and onFault function to
  494. handle the response from the server. We added this function for the successful result
  495. from the server. A successful event handler is run every time the connection is handled
  496. properly to the server.
  497. </para>
  498. <programlisting role="as"><![CDATA[
  499. private function onResult(result:Object):void {
  500. // Display the returned data
  501. trace(String(result));
  502. }
  503. ]]></programlisting>
  504. <para>
  505. The onFault function, is called if there was an invalid response from the server. This
  506. happens when there is an error on the server, the URL to the server is invalid, the
  507. remote service or method does not exist, and any other connection related issues.
  508. </para>
  509. <programlisting role="as"><![CDATA[
  510. private function onFault(fault:Object):void {
  511. trace(String(fault.description));
  512. }
  513. ]]></programlisting>
  514. <para>
  515. Adding in the ActionScript to make the remoting connection is now complete. Running the
  516. ZendExample file now makes a connection to Zend Amf. In review you have added the
  517. required variables to open a connection to the remote server, defined what methods
  518. should be used when your application receives a response from the server, and finally
  519. displayed the returned data to output via trace().
  520. </para>
  521. </sect2>
  522. </sect1>
  523. <!--
  524. vim:se ts=4 sw=4 et:
  525. -->