本文實例講述了Symfony2實現在doctrine中內置數據的方法。分享給大家供大家參考,具體如下:
我們在使用symfony的時候,有時需要在數據庫中內置一些數據,那么我們如何在doctrine中設置呢?
所幸,symfony已經為我們封裝好了。這里,我們需要用到DoctrineFixturesBundle。
第一步,在composer.json中引入所需的DoctrineFixturesBundle:
{ "require": { "doctrine/doctrine-fixtures-bundle": "2.2.*" }}
第二步,執行composer:
composer update doctrine/doctrine-fixtures-bundle
第三步,在內核(app/AppKernel.php)中注冊此bundle:
// ...public function registerBundles(){ $bundles = array( // ... new Doctrine/Bundle/FixturesBundle/DoctrineFixturesBundle(), // ... ); // ...}
第四步,在需要內置數據的bundle下創建一個PHP類文件,如src/Acme/HelloBundle/DataFixtures/ORM/LoadUserData.php,其代碼如下:
// src/Acme/HelloBundle/DataFixtures/ORM/LoadUserData.phpnamespace 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(); }}
第五步,通過console執行內置數據命令:
php app/console doctrine:fixtures:load #為防止數據庫中原先的值被清除,可使用 --append 參數
此命令有以下三個參數:
–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.
官方文檔:http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html
本文永久地址:http://blog.it985.com/6662.html
本文出自 IT985博客 ,轉載時請注明出處及相應鏈接。