0

Zend Framework 3 に基づいてサイトを開発しており、一部のモジュールでは電子メールを送信する必要があります。

そのために PERL Mail を使用しています。すべての電子メール送信リクエストを本番環境の Amazon SES サービスに転送します。開発には無料の gmail アカウントを使用しています。

私のアプリケーションでは、そのlocal.phpファイルを使用してメール構成をローカルに保存したいと考えていますproject/config/autoload directory。このようにして、開発と本番の両方で異なる構成を使用できます。local.phpそのため、ファイルに次のエントリを作成しました。

'mail' => [
   'host' => 'ssl://smtp.gmail.com',
   'port' => '465',
   'auth' => true,
   'username' => 'myusername@mydomain.com',
   'password' => 'mypassword',
]

モジュールのサービスとコントローラーからこれらのパラメーターを取得する方法がわからないことを除いて、すべて問題ありません。

このパラメーターにアクセスするために必要なサービスの例を次に示しますmodule/User/src/service/UserManagerService

class UserManager
{
    /**
     * Doctrine entity manager.
     * @var Doctrine\ORM\EntityManager
     */
    private $entityManager;  

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


    public function addUser($data) 
    {
        **// Need to access the configuration data from here to send email**
    }
}  

このサービスにはファクトリがあります。

<?php
namespace User\Service\Factory;

use Interop\Container\ContainerInterface;
use User\Service\UserManager;

class UserManagerFactory
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {        
        $entityManager = $container->get('doctrine.entitymanager.orm_default');

        return new UserManager($entityManager);
    }
}

私はこれらの ZF3 ファクトリ、サービス、およびコントローラにかなり慣れていないので、ここではほとんど迷いません。

このサービスの local.php ファイルに保存されているパラメータを取得するにはどうすればよいですか? そのアプローチはコントローラでも同じでしょうか?

4

1 に答える 1

2

設定は の下のコンテナに保存されますConfig。コンテナからサービスやその他のものを取得するのと同じように取得できます。これは、ファクトリを使用してコンテナーから取得したもの (サービス、コントローラー) に対して機能します。ベスト プラクティスは、ファクトリ内の構成オプションを取得し、それをサービスまたはコントローラーに渡すことです。

あなたの工場:

<?php

namespace User\Service\Factory;

use Interop\Container\ContainerInterface;
use User\Service\UserManager;

class UserManagerFactory
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');
        $config = $container->get('Config');

        return new UserManager($entityManager, $config['mail']);

        /* Or write this as:
        return new UserManager(
            $container->get('doctrine.entitymanager.orm_default'), 
            $container->get('Config')['mail']
        );
        */
    }
}

あなたのサービス:

<?php

use Doctrine\ORM\EntityManager

class UserManager
{
    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * @var array
     */
    private $mailConfig;

    public function __construct(EntityManager $entityManager, array $mailConfig)
    {
        $this->entityManager = $entityManager;
        $this->mailConfig = $mailConfig;
    }

    public function addUser($data)
    {
        var_dump($this->mailConfig);
    }
}
于 2016-11-30T16:14:12.947 に答える