Array array for an object in Symfony2 / Doctrine2

I use the DoctrineFixtures package to instantiate an object at design time. In my load () method of the ORM method, I define data as associative arrays and create an entity object in a loop.

<?php // ... public function load($manager) { $roleDefs = array( 'role-1' => array( 'role' => 'administrator' ), 'role-2' => array( 'role' => 'user' ), ); foreach($roleDefs as $key => $roleDef) { $role = new Role(); $role->setRole($roleDef['role']); $manager->persist($role); $this->addReference($key, $role); } $manager->flush(); } 

I always use the same array scheme. Each element of the array uses the property name (in the underscore notation) of the object as an index. If the entity structure becomes more complex, there are many lines of $entity->setMyProperty($def['my_property']); .

I think that the problem of matching property names with setter methods is a very common problem in Symfony and Doctrine, since this type of display is found in many situations (for example, displaying forms for entities).

Now I'm wondering if there is a built-in method that can be used for matching. It would be nice to have a solution like

 foreach($defs as $key => $def) { $entity = $magicMapper->getEntity('MyBundle:MyEntity', $def); // ... } 

Does anyone have an idea how this can be achieved?

Thanks a lot, Hacksteak

+7
source share
1 answer

Sometimes I use cycles when creating fixtures. I'm not sure if this solution meets your requirements, but I believe that the most flexible way to create fixtures and quickly add new properties over time, if you need to, is to do the following ... Assuming creating a bunch of blog posts

 // an array of blog post fixture values $posts = array( array( 'title' => 'Foo', 'text' => 'lorem' 'date' => new \DateTime('2011-12-01'), ), array( 'title' => 'Bar', 'text' => 'lorem' 'date' => new \DateTime('2011-12-02'), ), // more data... ); // loop over the posts foreach ($posts as $post) { // new entity $post = new Post(); // now loop over the properties of each post array... foreach ($post as $property => $value) { // create a setter $method = sprintf('set%s', ucwords($property)); // or you can cheat and omit ucwords() because PHP method calls are case insensitive // use the method as a variable variable to set your value $post->$method($value); } // persist the entity $em->persist($post); } 

This way you can add additional properties by simply adding new values ​​to your array.

+14
source

All Articles