我和Zend有点问题。我正在尝试制作一些虚假的HTTP请求,并在执行module->controller->action
之后,返回在该操作中设置的随机变量。就像使用view->assign(,)
设置的变量一样 - 我可以稍后从视图文件(.phtml)访问它们。
以下是我的代码的一部分:
/application/controller/IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function init(){}
public function indexAction()
{
#$this->view seems to be a NULL value from the fake request, so I can't pass variables to it
//$this->view->x = 'y';
echo 'test';
return array(
'x' => 'y'
);
}
}
/public/index2.php
<?php
//--cut--
$application->bootstrap();
$options = array(
'action' => 'index',
'controller' => 'index',
'module' => 'default'
);
if( isset($options['action'], $options['module'], $options['controller']) )
{
$request = new Zend_Controller_Request_Http ();
$request->setModuleName($options['module'])->setActionName($options['action'])->setControllerName($options['controller']);
$frontController = Zend_Controller_Front::getInstance ()->returnResponse ( true );
$response = new Zend_Controller_Response_Http ();
$frontController->getDispatcher ()->dispatch ( $request, $response );
echo '$response:<b>Zend_Controller_Response_Http</b><br>';
//This returns me the body of what I echo in the indexAction but not the variables.
var_dump($response);
}
非常感谢你!
答案 0 :(得分:0)
您需要为此扩展Zend_Controller_Action,因为标准Action没有收到返回的变量。
答案 1 :(得分:0)
如果要在调度请求时分配变量以进行查看,可以在indexAction中创建Zend_View实例并分配值,如下所示:
public function indexAction()
{
echo "test";
$view = new Zend_View();
$view->setBasePath(APPLICATION_PATH."/views/");
$view->x = 'y';
echo $view->render("index/index.phtml");
}
尝试在索引视图脚本中嵌入变量,响应的var_dump将包含回显的“test”和index.phtml输出。
如果要将数组返回给响应,请使用json:
public function indexAction()
{
$array = array('x' => 'y');
echo json_encode($array);
}
index2.php:
//.....
var_dump($response);
var_dump(json_decode($response->getBody()));
答案 2 :(得分:0)
您将无法以您尝试的方式(在视图/ MVC之外)获取视图参数。这是因为在您的情况下,操作控制器IndexController
仅在调度方法(IndexAction
)的持续时间内存在于内存中。
使用view
类定义的参数仅在调用view->render()
时引用,然后才生成HTML。
然而,您可以从控制器操作中的获取用户定义的变量(公共范围),如下所示:
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
/** The view class uses PHP's magic set/get/isset methods to
NULL any access to values that are protected (or more precisely
have a underscore _ prefix for the property name)
hence $this->_view = null;
**/
/** we do however have access to this view (or create a new one if not already
defined within the action controller) with: **/
$view = $this->initView();
/** An array of the public controller parameters **/
$viewParams = $view->getVars();
}
}
此外,现在可以简化调度这些请求的代码:
$front = Zend_Controller_Front::getInstance();
$front->setRequest(
new Zend_Controller_Request_Http()->setParams($options)
)->dispatch();
注意:我使用的是版本1.11