Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine entity object to array

Wants to convert doctrine entiry object to normal array, this is my code so far,

 $demo = $this->doctrine->em->find('Entity\User',2);

Getting entity object ,

Entity\User Object
(
[id:Entity\User:private] => 2
[username:Entity\User:private] => TestUser
[password:Entity\User:private] => 950715f3f83e20ee154995cd5a89ac75
[email:Entity\User:private] => [email protected]
[firm_id:Entity\User:private] => Entity\Firm Object
    (
        [id:Entity\Firm:private] => 16
        [company_name:Entity\Firm:private] => TestFirm
        [company_detail:Entity\Firm:private] => India
        [created_at:Entity\Firm:private] => DateTime Object
            (
                [date] => 2014-08-01 18:16:08
                [timezone_type] => 3
                [timezone] => Europe/Paris
            )

        [user:Entity\Firm:private] => 
    )

[created_at:Entity\User:private] => DateTime Object
    (
        [date] => 2014-08-01 15:12:36
        [timezone_type] => 3
        [timezone] => Europe/Paris
    )

[updated_at:Entity\User:private] => DateTime Object
    (
        [date] => 2014-08-01 15:12:36
        [timezone_type] => 3
        [timezone] => Europe/Paris
    )

[firm:protected] => 
) ,

Tried this ,But as per my requiremnet do not want to user doctrine_query. Thanks.

like image 457
Wit Wikky Avatar asked Aug 06 '14 10:08

Wit Wikky


5 Answers

You can try something like this,

    $result = $this->em->createQueryBuilder();
    $app_code = $result->select('p')
            ->from('YourUserBundle:User', 'p')
            ->where('p.id= :id')
            ->setParameter('id', 2)
            ->getQuery()
            ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

Another way,

 $this->em->getRepository('YourUserBundle:User')
      ->findBy(array('id'=>1));

Above will return an array but contains doctrine objects. Best way to return an array is using the doctrine query.

Hope this helps. Cheers!

like image 162
Anjana Silva Avatar answered Nov 01 '22 14:11

Anjana Silva


Note: If your reason for wanting an array representation of an entity is to convert it to JSON for an AJAX response, I recommend checking this Q&A: How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?. I particularly like the one about using the built-in JsonSerializable interface which is similar to my answer.


Since Doctrine does not provide a way to convert entities to associative arrays, you would have to do it yourself. One easy way is to create a base class that exposes a function that returns an array representation of the entity. This could be accomplished by having the base class function call get_object_vars on itself. This functions gets the accessible properties of the passed-in object and returns them as an associative array. Then you would simply have to extend this base class whenever you create an entity that you would want to convert to an array.

Here is a very simple example:

abstract class ArrayExpressible {
    public function toArray() {
        return get_object_vars($this);
    }
}

/** @Entity */
class User extends ArrayExpressible {

    /** @Id @Column(type="integer") @GeneratedValue */
    protected $id = 1; // initialized to 1 for testing

    /** @Column(type="string") */
    protected $username = 'abc';

    /** @Column(type="string") */
    protected $password = '123';

}

$user = new User();
print_r($user->toArray());
// Outputs: Array ( [id] => 1 [username] => abc [password] => 123 )

Note: You must make the entity's properties protected so the base class can access them using get_object_vars()


If for some reason you cannot extend from a base class (perhaps because you already extend a base class), you could at least create an interface and make sure your entities implement the interface. Then you will have to implement the toArray function inside each entity.

Example:

interface ArrayExpressible {
    public function toArray();
}

/** @Entity */
class User extends SomeBaseClass implements ArrayExpressible {

    /** @Id @Column(type="integer") @GeneratedValue */
    protected $id = 1; // initialized to 1 for testing

    /** @Column(type="string") */
    protected $username = 'abc';

    /** @Column(type="string") */
    protected $password = '123';

    public function toArray() {
        return get_object_vars($this);
        // alternatively, you could do:
        // return ['username' => $this->username, 'password' => '****']
    }

}

$user = new User;
print_r($user->toArray());
// Outputs: Array ( [id] => 1 [username] => abc [password] => 123 )
like image 20
Cave Johnson Avatar answered Nov 01 '22 13:11

Cave Johnson


If you alread have the object entity fetched form the database, you could also work with the DoctrineModule\Stdlib\Hydrator\DoctrineObject.

/**
 * Assume your entity for which you want to create an array is in $entityObject.
 * And it is an instance of YourEntity::class.
 */
$tmpObject = new DoctrineObject($this->entityManager, YourEntity::class);
$data = $tmpObject->extract($entityObject);

Now $data will contain your object as array.

P.S. I'm not sure this was possible when the question was asked.

like image 3
cb0 Avatar answered Nov 01 '22 14:11

cb0


I'm new to Symfony, but there is some working (but strange) way:

json_decode($this->container->get('serializer')->serialize($entity, 'json'))

like image 2
gorodezkiy Avatar answered Nov 01 '22 14:11

gorodezkiy


I needed a toArray() method that could work after hydration but the get_object_vars() trick did not work because of the lazy loading/proxy stuff in doctrine 2.x

so here is my dropin method

use Doctrine\Common\Inflector\Inflector;
...
public function toArray() {
    $methods = get_class_methods($this);
    $array = [];
    foreach ($methods as $methodName) {
        // remove methods with arguments
        $method = new \ReflectionMethod(static::class, $methodName);
        if ($method->getNumberOfParameters() > 0) continue;
        $matches = null;
        if (preg_match('/^get(.+)$/', $methodName, $matches)) {
            // beautify array keys
            $key = Inflector::tableize($matches[1]);
            // filter unwanted data
            if (in_array($key, ['object1', 'object2'])) continue;
            $array[$key] = call_user_func([$this, $methodName]);
        }
    }
    return $array;
}

feel free to improve it

like image 2
quazardous Avatar answered Nov 01 '22 14:11

quazardous