如何在模型中获取翻译器?
在内部 View 中我们可以使用此代码获取翻译
$this->translate('Text')
在 Controller 内部我们可以使用此代码获取翻译器
$translator=$this->getServiceLocator()->get('translator');
$translator->translate("Text") ;
但是如何在模型中获取翻译器呢?
我尝试了很多方法来在模型中获取服务定位器 其中 2 个
1)使用MVC事件
$e=new MvcEvent();
$sm=$e->getApplication()->getServiceManager();
$this->translator = $sm->get('translator');
如果我 pring $sm 它显示为空。但它在 Model.php onBootstrap 中工作正常
2)创建了一个实现ServiceLocatorAwareInterface的模型 SomeModel.php
<?php
namespace Web\Model;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class SomeModel implements ServiceLocatorAwareInterface
{
protected $services;
public function setServiceLocator(ServiceLocatorInterface $locator)
{
$this->services = $locator;
}
public function getServiceLocator()
{
return $this->services;
}
}
并在我的模型中使用它
$sl = new SomeModel();
$sm=$sl->getServiceManager();
var_dump($sm); exit;
$this->translator = $sm->get('translator');
这也打印 null。
最佳答案
如果您的模型中不需要 servicemanager 实例,只需向其注入(inject)转换器实例即可。
例如:
// Your model's constructor
class MyModel {
// Use the trait if your php version >= 5.4.0
use \Zend\I18n\Translator\TranslatorAwareTrait;
public function __construct( $translator )
{
$this->setTranslator( $translator );
}
public function modelMethodWhichNeedsToUseTranslator()
{
// ...
$text = $this->getTranslator()->translate('lorem ipsum');
// ...
}
}
当您首次在服务或 Controller 级别创建模型时
class someClass implements ServiceLocatorAwareInterface {
public function theMethodWhichCreatesYourModelInstance()
{
// ...
$sm = $this->getServiceLocator();
$model = new \Namespace\MyModel( $sm->get('translator') )
// ...
}
}
如果您需要在多个方法/类上实例化模型(new MyModel();),请考虑为其编写一个工厂。
这是一篇关于 Dependency Injection and PHP 的好文章由 Ralph Schindler 撰写,了解有关此方法的更多详细评论。
关于php - Zend Framework 2 模型中的转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16915911/