【问题标题】:Convert Entity to array in Symfony在 Symfony 中将实体转换为数组
【发布时间】:2014-03-23 00:52:12
【问题描述】:

我正在尝试从实体中获取多维数组。

Symfony Serializer 已经可以转换为 XML、JSON、YAML 等,但不能转换为数组。

我需要转换,因为我想要一个干净的var_dump。我现在的实体连接很少,完全不可读。

我怎样才能做到这一点?

【问题讨论】:

  • 我不想将结果作为数组 - 我将它用作实体,需要在其他地方转换为数组。
  • 有比“var_dumps”更好的调试应用程序的方法。尝试使用 xdebug - 这个工具作为调试器真的很棒。
  • 优先使用这个类doctrine-project.org/api/common/2.4/…和方法转储
  • 为什么需要干净的 var 转储?如果您只是使用它进行调试(正如@Cyprian 所说,有更好的方法来解决它。如果您希望将var dumps 用作编码的一部分,那么您真的不应该。但是猫的图片...

标签: php symfony doctrine-orm


【解决方案1】:

显然,可以将对象转换为数组,如下所示:

<?php

class Foo
{
    public $bar = 'barValue';
}

$foo = new Foo();

$arrayFoo = (array) $foo;

var_dump($arrayFoo);

这个will produce 类似:

array(1) {
    ["bar"]=> string(8) "barValue"
}

如果您有私有和受保护的属性,请查看此链接:https://ocramius.github.io/blog/fast-php-object-to-array-conversion/

从存储库查询中获取数组格式的实体

在您的 EntityRepository 中,您可以选择您的实体并使用 getArrayResult() 方法指定您想要的数组。
欲了解更多信息,请参阅Doctrine query result formats documentation

public function findByIdThenReturnArray($id){
    $query = $this->getEntityManager()
        ->createQuery("SELECT e FROM YourOwnBundle:Entity e WHERE e.id = :id")
        ->setParameter('id', $id);
    return $query->getArrayResult();
}

如果所有这些都不合适,您应该查看有关ArrayAccess 接口的 PHP 文档。
它以这种方式检索属性:echo $entity['Attribute'];

【讨论】:

  • getArrayResult 不将实体转换为数组 - 我有实体并希望将其转换为数组。
  • @GrekHmhmm 我更新了我的答案:使用 get_object_vars($entity)
  • get_object_vars($entity) 在我的应用程序 2.6 上返回空
  • 如果返回空可能是因为您的请求返回空结果。对结果请求执行“var_dump”
  • 如果属性是私有的,get_object_vars 将不起作用
【解决方案2】:

您实际上可以使用内置的序列化程序将教义实体转换为数组。实际上,我今天刚刚写了一篇关于此的博客文章: https://skylar.tech/detect-doctrine-entity-changes-without/

你基本上调用了 normalize 函数,它会给你你想要的:

$entityAsArray = $this->serializer->normalize($entity, null);

我建议查看我的帖子以获取有关某些怪癖的更多信息,但这应该完全符合您的要求,无需任何额外的依赖项或处理私有/受保护的字段。

【讨论】:

    【解决方案3】:

    我遇到了同样的问题,并尝试了其他 2 个答案。两者都不是很顺利。

    • $object = (array) $object; 在我的密钥中添加了很多额外的文本 名字。
    • 序列化程序没有使用我的active 属性,因为它前面没有is,而是boolean。它还改变了我的数据和数据本身的顺序。

    所以我在我的实体中创建了一个新函数:

    /**
     * Converts and returns current user object to an array.
     * 
     * @param $ignores | requires to be an array with string values matching the user object its private property names.
     */
    public function convertToArray(array $ignores = [])
    {
        $user = [
            'id' => $this->id,
            'username' => $this->username,
            'roles' => $this->roles,
            'password' => $this->password,
            'email' => $this->email,
            'amount_of_contracts' => $this->amount_of_contracts,
            'contract_start_date' => $this->contract_start_date,
            'contract_end_date' => $this->contract_end_date,
            'contract_hours' => $this->contract_hours,
            'holiday_hours' => $this->holiday_hours,
            'created_at' => $this->created_at,
            'created_by' => $this->created_by,
            'active' => $this->active,
        ];
    
        // Remove key/value if its in the ignores list.
        for ($i = 0; $i < count($ignores); $i++) { 
            if (array_key_exists($ignores[$i], $user)) {
                unset($user[$ignores[$i]]);
            }
        }
    
        return $user;
    }
    

    我基本上将我所有的属性都添加到了新的$user 数组中,并创建了一个额外的$ignores 变量,以确保可以忽略属性(以防您不想要所有属性)。

    您可以在控制器中使用它,如下所示:

    $user = new User();
    // Set user data...
    
    // ID and password are being ignored.
    $user = $user->convertToArray(["id", "password"]);
    

    【讨论】:

      猜你喜欢
      • 2016-06-18
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 2010-10-18
      • 2018-09-14
      相关资源
      最近更新 更多