当前位置:首页 > PHP教程 > PHP常见问题

Symfony2实现在doctrine中内置数据的方法

本文实例讲述了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 doctrinebundlefixturesbundledoctrinefixturesbundle(), // ... ); // ... }

第四步,在需要内置数据的bundle下创建一个php类文件,如src/acme/hellobundle/datafixtures/orm/loaduserdata.php,其代码如下:

// src/acme/hellobundle/datafixtures/orm/loaduserdata.php namespace acmehellobundledatafixturesorm; use doctrinecommondatafixturesfixtureinterface; use doctrinecommonpersistenceobjectmanager; use acmehellobundleentityuser; 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博客 ,转载时请注明出处及相应链接。

更多关于php框架相关内容感兴趣的读者可查看本站专题:《php优秀开发框架总结》,《codeigniter入门教程》,《ci(codeigniter)框架进阶教程》,《yii框架入门及常用技巧总结》及《thinkphp入门教程》

希望本文所述对大家基于symfony框架的php程序设计有所帮助。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!