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 ...
解?
如何在抽象类中使用/需要我需要的文件?
这不起作用:
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上找到更多细节
侧面说明:
public,protected和private)$client = SesClient::factory,将它们分配给属性,只创建一次实例.目前,每个方法调用一遍又一遍地创建相同的实例.那很糟sendEmail实例,并将返回值分配给$send.您不检查返回值,也不返回它.要么忽略返回值,要么返回它,以便检查它!require,require_once必要时使用.require在执行相同的代码块两次时使用会导致错误:重新声明函数/类.如果时间至关重要,你可以选择require(因为require_once导致更多的开销),但你必须知道你在做什么.require使用自动加载器spl_autoloader_registerfinal那么,答案是:
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)