I'm developing an API using Zend Framework 1.12.3. I'm using Zend_Rest_Route, but I would like to have hierarchical URLs:
- http://api.example.com/professors
- http://api.example.com/professors/:professorId
- http://api.example.com/professors/:professorId/subjects
- http://api.example.com/professors/:professorId/subjects/:subjectId
I'm considering of using this approach, since I'd have to assign certain subjects to certain professors, and I belive that this schema solves it neatly.
However, I'm having a hard time achieving hierarchical URLs. I've already tried:
Zend_Controller_Router_Route with Chains, in the config .ini file, but since both the controller and the action have to be specified, when accessing http://api.example.com/professors/:professorId/subjects it always pointed to the same action (i.e., whatever the call method was - POST, PUT, GET, DELETE - it always pointed to the action specified in the config .ini file). For example, had I specified the getAction in the config file, using chains it would always call the getAction, no matter what was the method I've used. Currently, when having a POST call, it actually calls the postAction() (similarly happens for PUT, GET, DELETE, PATCH, HEAD and OPTIONS). My Controller file looks like this:
class V1_ProfessorsController extends REST_Controller { public function optionsAction() { // code goes here } public function headAction() { // code goes here } public function indexAction() { // code goes here - list of resources } public function getAction() { // code goes here } public function postAction() { // code goes here } public function putAction() { // code goes here } public function patchAction() { // code goes here } public function deleteAction() { // code goes here } }
Subclassing the Zend_Rest_Route and overriding the match() function as pointed out here. The thing is, that while this does work when calling
http://api.example.com/professors/:professorId/subjects
, it still uses the same ProfessorsController that is used when callinghttp://api.example.com/professors
. I'm not sure about this, but I believe that it would be best having its own controller (e.g. ProfessorsSubjectsController).
Also, I've got a question. How should the hierarchical routes work? Would it be better to have different controllers for different resources/subresources? E.g., having ProfessorsController for http://api.example.com/professors/:professorId
and ProfessorsSubjectsController for http://api.example.com/professors/:professorId/subjects/:subjectId
?