This article describes the example of Symfony2 implementing the method of built-in data in doctrine. Share it with everyone for your reference, the details are as follows:
When we use symfony, sometimes we need to build some data into the database, so how do we set it up in doctrine?
Fortunately, symfony has already packaged it for us. Here, we need to use DoctrineFixturesBundle.
The first step is to introduce the required DoctrineFixturesBundle in composer.json:
{ "require": { "doctrine/doctrine-fixtures-bundle": "2.2.*" } }
The second step is to execute composer:
composer update doctrine/doctrine-fixtures-bundle
The third step is to register this bundle in the kernel (app/AppKernel.php):
// ... public function registerBundles() { $bundles = array( // ... new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(), // ... ); // ... }
The fourth step is to create a PHP class file under the bundle that requires built-in data, such as src/Acme/HelloBundle/DataFixtures/ORM/LoadUserData.php. The code is as follows:
// src/Acme/HelloBundle/DataFixtures/ORM/LoadUserData.php namespace Acme\HelloBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Acme\HelloBundle\Entity\User; class LoadUserData implements FixtureInterface { /** * {@inheritDoc} */ public function load(ObjectManager $manager) { $userAdmin = new User(); $userAdmin->setUsername('admin'); $userAdmin->setPassword('test'); $manager->persist($userAdmin); $manager->flush(); } }
The fifth step is to execute the built-in data command through the console:
php app/console doctrine:fixtures:load #为防止数据库中原先的值被清除,可使用 --append 参数
This command has the following three parameters:
–fixtures=/path/to/fixture – Use this option to manually specify the directory where the fixtures classes should be loaded;
–append – Use this flag to append data instead of deleting data before loading it (deleting first is the default behavior);
–em=manager_name – Manually specify the entity manager to use for loading the data.
Official documentation: http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html
The permanent address of this article: http://blog.it985.com/6662.html
This article comes from IT985 Blog. Please indicate the source and corresponding link when reprinting.
Readers who are interested in more content related to the PHP framework can check out the special topics of this site: "Summary of PHP Excellent Development Framework", "Introduction Tutorial on Codeigniter", "Advanced Tutorial on CI (CodeIgniter) Framework", "Introduction to Yii Framework and Summary of common techniques" and "ThinkPHP introductory tutorial"
I hope this article will be helpful to everyone’s PHP program design based on the Symfony framework.