zend-framework2 - 如何从 zend 框架 2 中的模型捕获 basePath?

标签 zend-framework2

我想捕捉像 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/

相关文章:

php - 如何在不使用工厂的情况下验证 Zend Framework 2 中的嵌套字段集

php - 如何将附加变量传递给匿名 TableGateway 方法参数?

php - 即使在成功操作后 Apigility 也会返回错误

zend-framework2 - ZF2 : Redis | Change dump. rdb 位置

php - 使用控制台安装 Zend Framework 2

php - Allow_Remove 不会删除集合

php - 如何在 zend 文字中转义?

zend-framework2 - 如何使用redirect()设置查询参数

zend-framework2 - Zend 框架 2 : Trying to add a selectbox to a form does not render values

mongodb - Zend Framework 2 + Doctrine ODM, "The Class was not found in the chain configured namespaces"错误?