例外:不允许序列化“闭包”

新手上路,请多包涵

所以我不确定我要向你们展示什么,如果你需要更多代码,请不要犹豫,问:

所以这个方法将在我们的应用程序中为 Zend 设置 initMailer:

 protected function _initMailer()
{
    if ('testing' !==  APPLICATION_ENV) {
        $this->bootstrap('Config');
        $options = $this->getOptions();
        $mail = new Zend_Application_Resource_Mail($options['mail']);
    }elseif ('testing'  ===  APPLICATION_ENV) {
        //change the mail transport only if dev or test
        if (APPLICATION_ENV <> 'production') {

            $callback = function()
            {
                return 'ZendMail_' . microtime(true) .'.tmp';
            };

            $mail = new Zend_Mail_Transport_File(
                array('path' => '/tmp/mail/',
                        'callback'=>$callback
                )
            );

            Zend_Mail::setDefaultTransport($mail);
        }
    }

    return $mail;
}

您可以看到其中的闭包。当我运行任何使用此代码的测试时,我得到:

 Exception: Serialization of 'Closure' is not allowed

因此与此“关闭”有关的所有测试都失败了。所以我在这里问你们我应该怎么做。

为了澄清上述内容,我们所做的只是说我们发送的任何电子邮件都希望将有关该电子邮件的信息存储在文件中 /tmp/mail/ 目录中的文件夹中。

原文由 TheWebs 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

显然匿名函数不能被序列化。

例子

$function = function () {
    return "ABC";
};
serialize($function); // would throw error

从您的代码中,您正在使用 Closure:

 $callback = function () // <---------------------- Issue
{
    return 'ZendMail_' . microtime(true) . '.tmp';
};

解决方案1: 替换为正常功能

例子

function emailCallback() {
    return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;

解决方案 2: 通过数组变量间接调用方法

如果您查看 http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html

    public function __construct($options = null)
   63     {
   64         if ($options instanceof Zend_Config) {
   65             $options = $options->toArray();
   66         } elseif (!is_array($options)) {
   67             $options = array();
   68         }
   69
   70         // Making sure we have some defaults to work with
   71         if (!isset($options['path'])) {
   72             $options['path'] = sys_get_temp_dir();
   73         }
   74         if (!isset($options['callback'])) {
   75             $options['callback'] = array($this, 'defaultCallback'); <- here
   76         }
   77
   78         $this->setOptions($options);
   79     }

您可以使用相同的方法发送回调

$callback = array($this,"aMethodInYourClass");

原文由 Baba 发布,翻译遵循 CC BY-SA 4.0 许可协议

PHP 不允许直接闭包序列化。但是您可以使用强大的类,例如 PHP Super Closure: https ://github.com/jeremeamia/super_closure

这个类使用起来非常简单,并且捆绑到队列管理器的 laravel 框架中。

来自 github 文档:

 $helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
    echo "{$greeting}, {$name}!\n";
});

$serialized = serialize($helloWorld);

原文由 Ifnot 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题