I am new to MVC and Zend, so I have little idea what I am doing at the moment, but here is my question.
The following code is my get method for an API I am attempting to build in order to learn both. It works as is, but given the sparsity of code I have seen in example methods, and the fact that Zend seems to do a lot for you, is there a better way of doing this? The code is something I cobbled together because the tutorial that I was walking through forgot to add the get method code.
public function getAction()
{
// action body
// Is there a better way to get the id from the URL?
$this->_getAllParams();
$request = $this->_request->getParams();
if (array_key_exists($request['id'], $this->_todo)){
$return[] = array($request['id'] => $this->_todo[$request['id']]);
}else{
// error code here or call some error method?
// do I do error coding here or send a message to some handler/helper?
}
echo Zend_Json::encode($return);
}
Essentially this will take a URL and pass json encode information that is currently stored in an array.
i.e.
http://restapi.local/api/1
displays:
[{"1":"Buy milk"}]
EDIT:
The routing apparently takes place in the bootstrap:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initRoutes()
{
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$restRoute = new Zend_Rest_Route($front);
$router->addRoute('default', $restRoute);
}
}
And below is the full ApiController.php:
class ApiController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
$this->_helper->viewRenderer->setNoRender(true);
$this->_todo = array (
"1" => "Buy milk",
"2" => "Pour glass of milk",
"3" => "Eat cookies"
);
}
public function indexAction()
{
// action body
echo Zend_Json::encode($this->_todo);
}
public function getAction()
{
// action body
$this->_getAllParams();
$request = $this->_request->getParams();
if (array_key_exists($request['id'], $this->_todo)){
$return[] = array($request['id'] => $this->_todo[$request['id']]);
}
echo Zend_Json::encode($return);
}
public function postAction()
{
// action body
$item = $this->_request->getPost('item');
$this->_todo[count($this->_todo) + 1] = $item;
echo Zend_Json::encode($this->_todo);
}
public function putAction()
{
// action body
}
public function deleteAction()
{
// action body
}
}
_todo
is. – Corbin Jun 23 '12 at 8:15