简体   繁体   English

在ZF2类中获取配置的简单方法

[英]Simple way to get config in ZF2 class

I want to create a simple class that will send a predefined email to given email address. 我想创建一个简单的类,将预定义的电子邮件发送到给定的电子邮件地址。 So I created the following class: 因此,我创建了以下类:

namespace Custom;

use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;

class Notification
{   
    public function sendEmailNotification($to)
    {
        try {
            $message = new Message();
            $message->addTo($to)
                ->addFrom('test@example.com')
                ->setSubject('Hello')
                ->setBody('Predefined email body');

            $transport = new SmtpTransport();
            $options   = new SmtpOptions(array(
                    'name'              => 'smtp.example.com',
                    'host'              => 'smtp.example.com',
                    'port'              => '587',
                    'connection_class'  => 'plain',
                    'connection_config' => array(
                            'username'  => 'test@example.com',
                            'password'  => 'somepasswd',
                            'ssl'       => 'tls',
                    ),
            ));
            $transport->setOptions($options);
            $transport->send($message);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}

From controller, the email is then sent with: 然后从控制器发送电子邮件至:

$notification = new \Custom\Notification();
$notification->sendEmailNotification('example@example.com');

This works as intended. 这按预期工作。

Next thing that I wanted to do is to move mail server configuration parameters into project configuration file ( local.php ). 我想做的下一件事是将邮件服务器配置参数移到项目配置文件( local.php )中。 Problem is - how can I get the configuration parameters in my \\Custom\\Notification class (which is not a controller)? 问题是-如何在\\ Custom \\ Notification类(不是控制器)中获取配置参数?

Solutions I have found so far seem too complicated to a beginner like me. 到目前为止,我发现的解决方案对于像我这样的初学者来说似乎太复杂了。 To do something like $config = $this->getServiceLocator()->get('Config'); 做类似$config = $this->getServiceLocator()->get('Config'); you have to do some kind of magic all around the project. 您必须在整个项目中做一些魔术。

Is there a simple way to get data from configuration file in a custom class? 有没有一种简单的方法可以从自定义类的配置文件中获取数据?

You have to use injection for your purpose. 您必须使用注射来达到目的。 Just create a factory for your controller, in which you inject the config to your controller. 只需为您的控制器创建一个工厂,即可在其中将配置注入到控制器中。

namespace Application\Controller\Service;

class YourControllerFactory 
{
    public function __invoke(ContainerInterface $container)
    {
        $serviceLocator = $container->getServiceLocator();
        $config = $serviceLocator->get('config');

        $controller = new YourController($config);

        return $controller;
    }
}

For this purpose your controller needs a constructor which takes the config as parameter. 为此,您的控制器需要一个将config作为参数的构造函数。

namespace Application\Controller;

class YourController extends AbstractActionController
{
    protected $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    public function indexAction()
    {
        // inject your notification class with the config
        $notification = new \Custom\Notification($this->config);
        $notification->sendEmailNotification('example@example.com');
    }
}

Therefore your notification class needs a constructor which takes the config as parameter. 因此,您的通知类需要一个使用config作为参数的构造函数。

Other approaches 其他方法

Another way solving your issue can be the registration of your notification class as a service. 解决问题的另一种方法是将通知类注册为服务。 Just create a factory for your notification class, in which you create all the needed stuff and then just inject it to your notification class. 只需为您的通知类创建一个工厂,即可在其中创建所有需要的内容,然后将其注入到通知类中。

namespace Application\Mail;

class Notification
{
    protected $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    public function sendEmailNotification($to)
    {

    }
}

The factory itself is simple as pie, because we 've seen nearly the same approach in the controller factory. 工厂本身就像馅饼一样简单,因为我们已经在控制器工厂中看到了几乎相同的方法。

namespace Application\Mail\Service;

class NotificationFactory
{
    public function __invoke(ContainerInterface $container)
    {
        $config = $container->get('config');
        $notification = new Notification($config);

        return $notification;
    }
}

Now you just have to note it in your module.config.php file in the service manager section. 现在,您只需要在服务管理器部分的module.config.php文件中对其进行注释module.config.php

'service_manager' => [
    'factories' => [
        Notification::class => NotificationFactory::class,
    ],
],

From now on you can access the notification class with the service container of zend framework 2. Remember the factory for your controller instance shown above? 从现在开始,您可以使用zend framework 2的服务容器访问通知类。还记得上面显示的控制器实例的工厂吗? Instead of injecting the config to your controller, just inject it with the notification itself. 与其将配置注入到控制器中,不如将其与通知本身一起注入。 Your notification class will be created with the needed config over the notification factory. 您的通知类将在通知工厂中使用所需的配置进行创建。

namespace Application\Controller\Service;

class YourControllerFactory 
{
    public function __invoke(ContainerInterface $container)
    {
        $serviceLocator = $container->getServiceLocator();
        $notification = $serviceLocator->get(Notification::class);

        return new YourController($notification);
    }
}

Have fun. 玩得开心。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM