【发布时间】:2013-03-13 00:39:55
【问题描述】:
我创建了一个名为AbstractApplicationForm 的抽象表单类。我希望通过Zend\ServiceManager\ServiceLocatorAwareInterface 将服务定位器注入其中以访问翻译器:
namespace Application\Form;
use Zend\Form\Form;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
abstract class AbstractApplicationForm
extends Form
implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
protected $translator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function getTranslator()
{
if (!$this->translator) {
$this->translator = $this->getServiceLocator()->get('translator');
}
return $this->translator;
}
}
我的申请表扩展了这个类,如下所示:
namespace Trade\Form;
use Zend\Captcha;
use Zend\Captcha\Image;
use Zend\Form\Element;
use Application\Form\AbstractApplicationForm;
class MemberForm extends AbstractApplicationForm
{
public function init()
{
$this->setAttribute('method', 'post');
// Add the elements to the form
$id = new Element\Hidden('id');
$first_name = new Element\Text('first_name');
$first_name->setLabel($this->getTranslator('First Name'))
这样,我就可以用getTranslator翻译标签了。
到目前为止一切顺利。在我的控制器操作中,我创建了这样的表单:
public function joinAction()
{
// Create and initialize the member form for join
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Trade\Form\MemberForm');
结果是 ServiceManager 异常:
Zend\ServiceManager\ServiceManager::get 无法为翻译器获取或创建实例
我没有在Module.php 或module.config.php 中定义任何其他内容,我认为我不需要。我在module.config.php 中定义了翻译器,如下所示:
'translator' => array(
'locale' => 'en_US',
'translation_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
当我将它放入控制器时效果很好:
$sm = $this->getServiceLocator();
$this->translator = $sm->get('translator');
所以翻译器配置实际上是正确的,但我无法在我的表单中检索它。 有人知道我做错了什么吗?
【问题讨论】: