Symfony2 writing data-fixtures

Symfony2 writing data-fixtures

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 🙂

You made it all the way down here so you must have enjoyed this post! You may also like:

Symfony2 Assetic Darko Goles
Darko Goles, | 6

Symfony2 Assetic

Doctrine DBAL with Symfony2 Darko Goles
Darko Goles, | 4

Doctrine DBAL with Symfony2

Symfony2 Doctrine2 transactions Darko Goles
Darko Goles, | 10

Symfony2 Doctrine2 transactions

3 comments

    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>.

Tell us about your project

Drop us a line. We'd love to know more about your project.