我想捕捉像 View 这样的基本路径。在 View 中,使用 $this->basePath();
等辅助函数可以轻松获取基本路径,我想从模型中获取基本路径值。
最佳答案
为您的模型添加 getter/setter:
测试模型.php
<?php
class TestModel
{
protected $_basePath;
/**
* @param string
*/
public function setBasePath($path)
{
$this->_basePath = $path;
}
}
现在在实例化模型时注入(inject)它
服务管理器配置:
'factories' => array(
'Application\Model\TestModel' => function($sm){
$model= new \Application\Model\TestModel();
// Just grab what we want from the view helper
$helper = $sm->get('viewhelpermanager')->get('basePath');
$path = $helper(); // or $helper('filenamehere') for added file path
// Alternatively you can just use the request to get the path
//$path = $sm->get('Request')->getBasePath();
$model->setBasePath($path);
return $model;
},
如果您的模型中有可用的服务管理器/服务定位器,您可以使用上述方法之一直接获取模型中的值。
$path = $serviceManager->get('Request')->getBasePath();
如果您查看 ViewHelper 是如何实例化的,您会发现它首先检查配置:
$config = $serviceLocator->get('Config');
if (isset($config['view_manager']) && isset($config['view_manager']['base_path'])) {
$basePath = $config['view_manager']['base_path'];
}
else {
$basePath = $serviceLocator->get('Request')->getBasePath();
}
关于zend-framework2 - 如何从 zend 框架 2 中的模型捕获 basePath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16934414/