我创建了一个名为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
or中定义任何其他内容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');
所以翻译器配置实际上是正确的,但我无法在我的表单中检索它。有人知道我在做什么错吗?