我想为给定的请求设置一个MVC的每个组件的basePath
。我的意思是,当我调用这些方法时,我想获得相同的结果,可以说 '/spam/ham/'
:
echo $this->headLink()->prependStylesheet($this->basePath() . '/styles.css') // $this->basePath() has to be '/spam/ham/'
$this->getServiceLocator()
->get('viewhelpermanager')
->get('headLink')
->rependStylesheet($this->getRequest()->getBasePath() . '/styles.css') // $this->setRequest()->getBasePath() has to be /spam/ham/
如何为我已经找到的第一种情况设置basePath
,这是我的问题。顺便说一句,原始手册没有我从答案中收到的任何信息。
现在第二个 - 必须在Request
中设置basePath
:
$this->getRequest()->getBasePath()
在这里,我找到了一些答案,实际上实际上根本不起作用http://zend-framework-community.634137.n4.n.nabble.com/setting-the-the-base-url-in-in-in-zf2-mvc-td3946284.html。正如这里所说的StaticEventManager
已弃用,所以我用SharedEventManager
更改了它:
// In my ApplicationModule.php
namespace Application;
use ZendEventManagerSharedEventManager
class Module {
public function init() {
$events = new SharedEventManager();
$events->attach('bootstrap', 'bootstrap', array($this, 'registerBasePath'));
}
public function registerBasePath($e) {
$modules = $e->getParam('modules');
$config = $modules->getMergedConfig();
$app = $e->getParam('application');
$request = $app->getRequest();
$request->setBasePath($config->base_path);
}
}
}
,在我的modules/Application/configs/module.config.php
中,我添加了:
'base_path' => '/spam/ham/'
,但它不起作用。问题是:
1)运行永远不会出现registerBasePath
功能。但必须这样做。我已经在init
函数中与听众一起附上了一个事件。
2)当我更改SharedEventManager
的EventManager
时,它恰好是registerBasePath
功能,但抛出了exeption:
Fatal error: Call to undefined method ZendEventManagerEventManager::getParam()
我做错了什么?为什么程序的运行不访问registerBasePath
函数?如果这是全球设置basePath
的唯一方法,那么如何做正确的操作?
我知道文档缺乏这些东西。但是您正是正确的选择:
- 早点(在Bootstrap上)
- 从应用程序中获取请求
- 在请求中设置基本路径
文档缺乏此信息,您所指的帖子很旧。最快,最简单的方法是使用onBootstrap()
方法:
namespace MyModule;
class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$app->getRequest()->setBasePath('/foo/bar');
}
}
如果要从配置中获取基本路径,则可以在此处加载服务管理器:
namespace MyModule;
class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$config = $sm->get('config');
$path = $config->base_path;
$app->getRequest()->setBasePath($path);
}
}