PHP Amazon Ses作为抽象类会产生使用致命错误

Dan*_*Dan 0 php amazon-web-services amazon-ses

我正在使用亚马逊简单电子邮件服务,并尝试将其作为抽象类实现,以便我可以根据需要简单地使用它.

问题

使用时出现问题,我无法弄清楚如何要求使用Ses作为抽象类所需的文件和类而不会产生错误.

require 'lib/aws/aws-autoloader.php';

use Aws\Common\Enum\Region;
use Aws\Ses\SesClient;

abstract class simpleemail {

    function sendSesEmail($to, $subject, $body, $bodyHtml){

        try {   
            $client = SesClient::factory(array(
                'key' => "",
                'secret' => "",
                'region' => Region::US_EAST_1
            ));

            $send = $client->sendEmail(array(
                'Source' => 'Name <no-reply@contact.com>',
                'Destination' => array('ToAddresses' => array($to)),
                'Message' => array('Subject' => array('Data' => $subject), 'Body' => array('Html' => array('Data' => $bodyHtml)))));

            return true;
        }
        catch(Exception $e){
            echo $e->getMessage();
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误消息

Fatal error: Class 'Aes\Ses\SesClient' not found in ....

我试过更改use为要求,但后来得到:

require 'lib/aws/Aws/Common/Enum/Region.php';
require 'lib/aws/Aws/Ses/SesClient.php';
Run Code Online (Sandbox Code Playgroud)

Fatal error: 'SesClient' not found in ...

解?

如何在抽象类中使用/需要我需要的文件?

Eli*_*gem 5

这不起作用:

abstract class simpleemail
{
    public function sendSesEmail()
    {
        use Aws\Common\Enum\Region;
        use Aws\Ses\SesClient;
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

use语句基本上是在编译时处理的导入,因此它们不能作用域.他们必须移动到外部范围(课外).
如果你想要他们的范围,你必须要么手动require,或使用class_alias.有关详细信息,
请查看此问题的答案.甚至可以在php.net上找到更多细节

侧面说明:

  • 请遵循PHP-FIG所描述的编码标准.他们不是官方的,但是Zend,Symfony ......事实上,所有主要参与者都赞同他们.
  • 请的习惯中得到总是指定accessmodifiers( public,protectedprivate)
  • 在创建类似的实例时$client = SesClient::factory,将它们分配给属性,只创建一次实例.目前,每个方法调用一遍又一遍地创建相同的实例.那很糟
  • 使用属性时:在类定义中包含它们!
  • 您正在调用sendEmail实例,并将返回值分配给$send.您不检查返回值,也不返回它.要么忽略返回值,要么返回它,以便检查它!
  • 永远不要使用require,require_once必要时使用.require在执行相同的代码块两次时使用会导致错误:重新声明函数/类.如果时间至关重要,你可以选择require(因为require_once导致更多的开销),但你必须知道你在做什么.
  • 不要require使用自动加载器spl_autoloader_register
  • 请记住:抽象类无法实例化,只有它们的子节点......子节点也可以覆盖抽象类中声明的方法.将关键方法声明为final

那么,答案是:

use Aws\Common\Enum\Region;
use Aws\Ses\SesClient;
abstract class simpleemail
{
    protected $client = null;
    final public function sendSesEmail()
    {
        $client = $this->getClient();//lazy-loads the client instance
        return $client->sendEmail(/* ... */);//return the result
    }
    //lazy-loader
    protected function getClient()
    {
        if ($this->client === null)
        {
            $this->client = SesClient::factory(array(
                'key' => "",
                'secret' => "",
                'region' => Region::US_EAST_1
            ));
        }
        return $this->client;
    }
}
Run Code Online (Sandbox Code Playgroud)