我是zend.i的新手,需要使用带有JSON响应的Zend_Json_Server在zend中创建web服务。我在这里定义了api控制器..
<?php
class ApiController extends Zend_Controller_Action
{
public function init()
{ }
public function indexAction()
{ }
public function restAction()
{
// disable layouts and renderers
$this->getHelper('viewRenderer')->setNoRender ( true );
// initialize REST server
$server = new Zend_Json_Server();
// set REST service class
$server->setClass('Test_Return');
// handle request
if ('GET' == $_SERVER['REQUEST_METHOD']) {
$server->setTarget('/json-rpc.php')
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();
// Set Dojo compatibility:
// $smd->setDojoCompatible(true);
header('Content-Type: application/json');
echo $smd;
}
$server->handle();
}
}
?>
Test_Return在Library / Test中定义 Test_Return代码在这里..
<?php
class Test_Return {
public function add($x, $y)
{
return $x + $y;
}
public function subtract($x, $y)
{
return $x - $y;
}
public function multiply($x, $y)
{
return $x * $y;
}
public function divide($x, $y)
{
return $x / $y;
}
} ?>
如何调用特定表达式。
答案 0 :(得分:1)
如索引here中所述,您可以创建zend_rest_server的实例,添加您的方法并运行它。应在url中指定方法。我觉得你选择了zend 2来实现更好的实现
答案 1 :(得分:0)
Zend_Json_Server初始化应该在你的public / index.php
中defined('APPLICATION_PATH') ||
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
defined('APPLICATION_ENV') ||
define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
set_include_path(implode(PATH_SEPARATOR, array(
dirname(dirname(__FILE__)) . '/libs',
get_include_path(),
)));
require_once 'Zend/Application.php';
$application = new Zend_Application(
APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$application->getBootstrap()->bootstrap();
// Instantiate server ...
$server = new Zend_Json_Server();
include_once APPLICATION_PATH . '/Calculator.php';
$server->setClass(new Calculator());
if ('GET' == $_SERVER['REQUEST_METHOD'])
{
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget('/api/1.0/jsonrpc.php')->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return;
}
$server->handle();
$application->bootstrap()->run();
在命令行上使用curl你什么都看不见;-)。这让我感到沮丧。
curl -H "Content-Type: application/json" -d '{"method":"add","x":5,"y":10}' http://zend.rest.server/api/1.0/jsonrpc.php
在浏览器上,您可以使用此jQuery plugin
app = jQuery.Zend.jsonrpc({url: '/api/1.0/jsonrpc'});
app.add(5, 5);
{"result":10,"id":"1","jsonrpc":"2.0"}
您可能希望按照here描述的步骤进行操作。
如果可以的话,我建议您保留zend版本,因为zend2.X.X可以更好地支持休息服务。