Handling Input with Zend Framework outside MVC

2019-08-25 01:46发布

问题:

In a classic Zend Framework MVC setup, there seems to be access to a generic _request object from within the model/view/controller instance as outlined here:

$this->_request->getPost('variablename');

is this request object somehow available in a non-MVC setup as well?

If yes: how would I initialize and access it?

回答1:

I would not use the Zend_Controller_Request_* objects outside ZF's MVC structure (even if possible). You can see by the class name already that it belongs to the controller package and it's API exposes a number of methods that are completely targeted at being used within ZF's MVC and these are inherited by all subtypes.

That's okay when using ZF's MVC, but for usage outside of that the Request Objects do too much. The idea of a Request object is to encapsulate and maybe decouple the current Request environment from the Superglobals (which ZF doesn't. It just sits on top). All that extra stuff about modules, controllers and actions shouldn't be part of it in my opinion. It makes only sense in ZF.

Writing a Request object isn't difficult, so I'm sure you can easily come up with a more lightweight version. Here is some basic examples:

  • http://www.phpdesignpatterns.de/auflage-2/downloads/code/PHP-Design-Pattern-Kapitel-8.zip
  • http://github.com/sebastianbergmann/php-mvc-ukernel/blob/master/Request.php
  • http://github.com/spriebsch/MVC/blob/master/src/Request.php

In the end it's your choice though.



回答2:

The front controller initalizes the request and response objects and passes them to the router. The router calls the requested action, and (usually) appends the returned content to the response. So these objects are available in the Controller layer from the MVC.

Edit:
The frontController uses the following code to set up the request:

$request = new Zend_Controller_Request_Http();

Using the request object this way is very straighforward, so using it outside from the Zend Controller or the Application module shouldn't be a problem. Zend_Controller_Request_Http uses Zend_Uri.