获取Blob类型Doctrine实体属性仅返回一次数据 [英] Getting blob type Doctrine entity property returns data only once

查看:53
本文介绍了获取Blob类型Doctrine实体属性仅返回一次数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Doctrine将选项/奇数数据的各个位存储在数组中,并将其序列化到数据库中,并在其中将其存储为blob.直到今天,一切都运转良好,我不得不两次获取该数组,并注意到它只有在第一次才获得正确的值.任何连续的尝试都将返回false,这是unserialize/stream_get_contents在失败时返回的结果.

I use Doctrine to store options/various bits of odd data in an array and serialise it to database where it gets stored as a blob. Everything was working fine until today I had to get that array twice and noticed that it gets the correct value only the first time. Any successive attempts return false, which is what unserialize/stream_get_contents returns on failure.

我最好的猜测是,该学说在获取数据后将其关闭,但这没有多大意义.我需要整个请求中都可用的数据.我不是流专家,所以:

My best guess is that doctrine closes the stream after it fetches the data, but it doesn't make much sense. I need the data to be available throughout the request. I'm not an expert with streams so:

如何多次获取Blob数据或阻止流关闭?

Doctrine实体及其方法:

Doctrine entity and it's methods:

/**
 * @var resource
 *
 * @ORM\Column(name="options", type="blob")
 */
private $options;

/**
 * Set options
 *
 * @param array $options
 *
 * @return Campaign
 */
public function setOptions($options)
{
    $this->options = serialize($options);

    return $this;
}

/**
 * Get options
 *
 * @return array
 */
public function getOptions()
{
    return unserialize(stream_get_contents($this->options));
}

检索序列化的选项数组:

Retrieve serialized options array:

$campaign   = $this->em->getRepository('TreasureForgeMessageBundle:Campaign')->find(1);
$options1   = $campaign->getOptions(); // Correct options array
$options2   = $campaign->getOptions(); // false
$options3   = $campaign->getOptions(); // false

非常感谢!

推荐答案

您遇到的问题是因为您没有 rewind()您在两次读取操作之间的句柄.

The problem you are experiencing occur because you do not rewind() your handle in between read operations.

但是,考虑到性能,在每次访问时对选项数组进行反序列化是一个坏主意. $ options 字符串在每次访问时都必须转换为数组.相反,您应该告诉主义 $ options 是一个数组,只有在从数据库读取数据或将数据写入数据库时​​,该数组才会被自动序列化和反序列化:

However, unserializing the option array on each access is a bad idea considering performance. The $options string would have to be converted to an array on each access. Instead, you should tell doctrine that $options is an array, which will then be automatically serialized and unserialized only when data is read from and written to the database:

/**
 * @var array
 *
 * @ORM\Column(name="options", type="array")
 */
private $options;

/**
 * Set options
 *
 * @param array $options
 *
 * @return Campaign
 */
public function setOptions($options)
{
    $this->options = $options;

    return $this;
}

/**
 * Get options
 *
 * @return array
 */
public function getOptions()
{
    return $this->options;
}

更新:

此处中描述了数组类型

这篇关于获取Blob类型Doctrine实体属性仅返回一次数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆