views:

416

answers:

2

How to access Request object within Form method? I assume it's somehow possible to access controller's request object using ActionHelper inside Form methods, but writing a new class for such a task seems to be excessive.

Or should I somehow save controller's Request to Zend_Registry and access Registry item in Form?

+1  A: 
$request = Zend_Controller_Front::getInstance()->getRequest()

?

Andrei Serdeliuc
A: 

Although the registry method (1) as well as accessing the singleton front-controller (2) both will work, there is some major downside with both methods: they introduce a hard dependeny on either the Zend_Controller_Front or the Zend_Registry and the request key as well as the Zend_Controller_Request_Abstract.

// (1)
// in bootstrap e.g.
Zend_Registry::set('request', Zend_Controller_Front::getInstance()->getRequest());

// in form method
$request = Zend_Registry::get('request');

// (2)
//in form method
$request = Zend_Controller_Front::getInstance()->getRequest();

I think the best way would be to either inject the request-object into the form via the form's constructor or via a setter on the form or even better just to inject the request parameters as an array.

// form class (constructor-injection presumed)
class My_Form extends Zend_Form
{
    /**
     * @var Zend_Controller_Request_Abstract
     */
    protected $_request;

    public function __construct(Zend_Controller_Request_Abstract $request, $options = null)
    {
        parent:: __construct($options);
        $this->_request = $request;
    }       
}
// or inject only parameters
class My_Form extends Zend_Form
{
    /**
     * @var array
     */
    protected $_params;

    public function __construct(array $params, $options = null)
    {
        parent:: __construct($options);
        $this->_params= $params;
    }       
}
Stefan Gehrig