如何在TWIG文件中显示LONGBLOB字段数据



我在Symfony2工作。我在表中有一个使用LONGBLOB的字段。现在我想显示字段数据。当我显示这个LONGBLOB字段数据时,它显示的是这样的文本 Resource id #404 但实际上在字段中我存储了虚拟文本。

这是我的默认控制文件代码

DefaultController.php

function video_showAction($id)
{
    $em = $this->getDoctrine()->getManager();       
    $video = $em->getRepository('MyBundle:Video')->find($id);
    return $this->render('MyBundle:Default:VideoShow.html.twig', array('qShow' => $video ));
}

VideoShow.html.twig

Description: {{ qShow.description }}
// it will display  "Resource id #404"

如何显示实际数据而不是引用

正如您在自己的回答中提到的,您应该重写getter函数。

我建议这样做:

private $descriptionAsText = null;
public function getDescription()
{
    if (is_null($this->descriptionAsText))
    {
       $this->descriptionAsText = stream_get_contents($this->description);
    }
    return $this->descriptionAsText;
}

如果你的流可以在实体的同一实例中改变,你最终可以使用:

public function getDescription()
{
    rewind($this->description);
    return stream_get_contents($this->description);
}

我不喜欢你现在的方法,如果你需要使用{{ qShow.description }}两次或更多次,你会因为你的流偏移而遇到麻烦。

您需要在每次执行stream_get_contents时倒带您的资源,因为它将偏移量放置在流的末尾(或指定的长度)。

您可以使用以下代码重现此行为:

<?php
file_put_contents("/tmp/test.txt", "Hello, world!");
$handle = fopen("/tmp/test.txt", "r");
$contents = stream_get_contents($handle);
echo "Contents A = {$contents}n"; // Contents A = Hello, world!
$contents = stream_get_contents($handle);
echo "Contents B = {$contents}n"; // Contents B =
fclose($handle);

这个行为从PHP 5.3开始就存在了(我猜),所以如果你在Codepad(使用5.2.5)上尝试这个代码,你将无法复制。

我找到了解决方案。我只需要使用stream_get_contents。我把这个放到了实体的Getter方法中。这样的

MyEntity.php

// Getter Function need to be change like this
public function getDescription()
{
    if ($this->description != '')
        return stream_get_contents($this->description);
    return $this->description;
}

现在当我显示内容时,它显示了资源Id包含的实际数据

要使用LONGBLOB,首先需要完成以下工作。以下链接详细描述了这些工作,请检查您是否完成了所有工作,然后再尝试在您的小枝文件中显示您的qShow.description。我认为"资源id #404"错误说你有问题,你有404 id号读取资源。

http://symfony2.ylly.fr/add-new-data-type-in-doctrine-2-in-symfony-2-jordscream/

最新更新