ZF2 - 如何在我的模型中获取应用程序配置项?

ZF2 - How do I get application config items within my model?

在我的工作中,我正在处理 ZF2 上的遗留应用程序 运行。有一种模型可以向不同的地址发送各种不同的电子邮件。他们的共同点是他们都需要密件抄送一个特定的地址。

起初,我在脑海中诅咒以前的开发人员,因为他愚蠢地将电子邮件地址硬编码在一个文件中 20 次不同的时间。我认为通过简单的调用 $this->config->get('x') 获取应用程序配置是小菜一碟(比如 Laravel) 或沿线的内容。现在我发现自己感觉很糟糕,因为我理解为什么以前的开发人员对电子邮件地址进行硬编码。

所以对于这个问题,我到底如何从模型中的 application.config.php 中获取配置项?我一直在阅读我需要如何实现 ServiceLocaterAware 接口。这真的有必要吗?必须有一种方法可以轻松获取配置,对吧?!?

您需要服务定位器/服务管理器

在您的控制器中:

public function xxxAction()
{
    $sm      = $this->getServiceLocator();
    $config  = $sm->get('config');
}

How the hell do I grab a config item from application.config.php inside the model?

你不应该在里面这样做,在'外面'。

将您的模型 class 注册为 module.config.php 中的服务。

'service_manager' => [
    'factories' => [
        'Email\Model\EmailModel' => 'Email\Model\EmailModelFactory',
    ]
],

然后创建工厂 Email\Model\EmailModelFactory,这使用服务管理器获取 'email' 配置密钥并将其注入模型的构造函数。

namespace Email\Model;

use Email\Model\EmailModel;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;

class EmailModelFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new EmailModel($this->getEmailOptions($serviceLocator));
    }

    // Return the email options
    public function getEmailOptions(ServiceLocatorInterface $serviceLocator)
    {
        $options = $serviceLocator->get('config');
        return $options['email'];
    }
}

您现在遇到的问题是对模型的所有调用 classes 都必须使用 $serviceManager->get('Email\Model\EmailModel')(而不是 new \Email\Model\EmailModel)才能注入配置。即使没有看到您的任何遗留应用程序,我猜想这也很困难。

模型不应该负责发送邮件;您可以将其替换为服务 class,例如'EmailService' 并为此 class.

重复上面的注入示例
EmailService::send(EmailModel $email, array $options);

这将使您的模型保持独立,并且无需替换对 new Model 等的调用。