Symfony2 writing data-fixtures

Featured Image

In last article about fixtures I wrote about manual setup for using data-fixtures with your Symfony2 project.
Now it’s time to write first data fixture.

Inside your bundle, create folder called: DataFixtures.

We are going to use Doctrine ORM with that so create folder inside called ‘ORM’.

Inside that folder create new file called: FixtureLoader.php

<?php
//Surgeworks\AdminBundle\DataFixtures\ORM\FixtureLoader.php
 
namespace Surgeworks\AdminBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Surgeworks\AdminBundle\Entity\User;
use Surgeworks\AdminBundle\Entity\Role;
use Surgeworks\AdminBundle\Entity\AttributeType;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
 
class FixtureLoader implements FixtureInterface {
 
public function load($manager) {
   $roleSA = new Role();
   $roleSA->setName('ROLE_SUPER_ADMINISTRATOR');
   $manager->persist($roleSA);
   $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
 
   $user = new User();
   $user->setFirstName('Darko');
   $user->setLastName('Goleš');
   $user->setEmail('darko.goles@surgeworks.com');
   $user->setUsername('darko.goles');
   $user->setSalt(md5(time()));
   $password = $encoder->encodePassword(
       'dont_want_to_tell_you', $user->getSalt());
   $user->setPassword($password);
   $user->getUserRoles()->add($roleSA);
   $manager->persist($user);
 
   $manager->flush();
 
}
 
}

Fire up the console, cd to app folder of you project and write:

php console doctrine:fixtures:load

Command purges the database and inserts fixtures inside.
That’s it for now,  Cheers 🙂


3 comments

  1. this is first time i visit your impressive blog. I don’t know about magento, after visit this page i have new insight at least. thank you 🙂

    1. @David, is it really comment on my post or just the way for you to get more backlinks?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.