Chad 2010-10-04
Symfony可以引用外部的类库, 1.4当然也不例外。说到类库,不能不提Zend Framework的Zend lib[1]。Zend lib类库包含了很多通用类,功能包括发邮件、数据库访问、权限控制、缓存控制、搜索等等。值得一提的是Zend_Amf[2]支持和Flash/Flex直接以AMF(Action Message Format)交换数据,由于AMF不像SOAP那样用XML来装载数据,所以在传输上有一定优势。但SOAP更为广泛被各种编程语言用来跟其它语言交换数据。
在这里讲讲在Symfony 1.4下使用Zend_Soap搭建Soap Server。
首先要做的是配置Zend的autoloader。在将Zend Lib复制到Symfony的lib/vendor/目录下后,修改ProjectConfiguration.class.php配置文件:
- // config/ProjectConfiguration.class.php
- class ProjectConfiguration extends sfProjectConfiguration {
- protected static $zendLoaded = false;
- public function setup() {
- $this->enablePlugins('sfDoctrinePlugin');
- $this->enablePlugins('sfDoctrineGuardPlugin');
- self::registerZend();
- }
- public static function registerZend() {
- if (self::$zendLoaded) {
- return;
- }
- set_include_path(
- sfConfig::get('sf_lib_dir') . '/vendor' . PATH_SEPARATOR . get_include_path()
- );
- require_once sfConfig::get('sf_lib_dir') . '/vendor/Zend/loader/Autoloader.php';
- Zend_Loader_Autoloader::getInstance();
- self::$zendLoaded = true;
- }
- }
然后,创建自己的Soap Function类:
- class TestService {
- /**
- *
- * @param string $name
- * @return string
- */
- public function sayHelloTo($name){
- return "Hello! {$name}";
- }
- }
这里注意一定要给方法加上php docblocks,标明方法的参数和返回值的类型,以让下面提到的Zend_Soap_AutoDiscover类自动生成WSDL。
接着,就可以创建一个方法专门用来生成WSDL(Web Services Description Language)。要做这个功能,Zend Framework的Soap AutoDiscover就显得很好用:
- class serviceActions extends sfActions {
- public function executeWsdl(sfWebRequest $request) {
- try {
- $wsdl = new Zend_Soap_AutoDiscover();
- $wsdl->setClass('TestService');
- $wsdl->handle();
- } catch (Exception $e) {
- $this->logMessage($e->getMessage());
- }
- return sfView::NONE;
- }
- // ...
再下来就是提供让外部访问的API了:
- soap_test:
- url: /service/test
- param: { module: service, action: index }
- class serviceActions extends sfActions {
- // ...
- public function executeIndex(sfWebRequest $request) {
- $this->forwardIf(null !== $request->getParameter('wsdl'), 'service', 'wsdl');
- try {
- $wsdl = $this->generateUrl('soap_test', array(), true).'?wsdl';
- $server = new Zend_Soap_Server($wsdl);
- $server->setClass('TestService');
- $server->setReturnResponse(true);
- $this->renderText($server->handle());
- } catch (Exception $e) {
- $this->logMessage($e->getMessage());
- }
- return sfView::NONE;
- }
- // ...
就这样,Symfony下的Soap Server就搭建完成了,不用reinvent the wheel就是爽。。。
最后,写个方法来测试一下:
- public function executeTestClient(sfWebRequest $request){
- try{
- $client = new Zend_Soap_Client('http://inluck.local/service/test?wsdl');
- $result = $client->sayHelloTo($request->getParameter('name','Chad'));
- } catch (Exception $e) {
- $this->logMessage($e->getMessage());
- }
- echo $result;
- return sfView::NONE;
- }
运行成功,大功告成!
Reference:
1. http://framework.zend.com/
2. http://framework.zend.com/manual/en/zend.amf.html
3. http://www.slideshare.net/hhamon/exposer-des-services-web-soap-et-rest-avec-symfony-14-et-zend-framework