Symfony2實(shí)現(xiàn)在doctrine中內(nèi)置數(shù)據(jù)的方法
本文實(shí)例講述了Symfony2實(shí)現(xiàn)在doctrine中內(nèi)置數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
我們?cè)谑褂胹ymfony的時(shí)候,有時(shí)需要在數(shù)據(jù)庫(kù)中內(nèi)置一些數(shù)據(jù),那么我們?nèi)绾卧赿octrine中設(shè)置呢?
所幸,symfony已經(jīng)為我們封裝好了。這里,我們需要用到DoctrineFixturesBundle。
第一步,在composer.json中引入所需的DoctrineFixturesBundle:
{
"require": {
"doctrine/doctrine-fixtures-bundle": "2.2.*"
}
}
第二步,執(zhí)行composer:
composer update doctrine/doctrine-fixtures-bundle
第三步,在內(nèi)核(app/AppKernel.php)中注冊(cè)此bundle:
// ...
public function registerBundles()
{
$bundles = array(
// ...
new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
// ...
);
// ...
}
第四步,在需要內(nèi)置數(shù)據(jù)的bundle下創(chuàng)建一個(gè)PHP類(lèi)文件,如src/Acme/HelloBundle/DataFixtures/ORM/LoadUserData.php,其代碼如下:
// 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();
}
}
第五步,通過(guò)console執(zhí)行內(nèi)置數(shù)據(jù)命令:
php app/console doctrine:fixtures:load #為防止數(shù)據(jù)庫(kù)中原先的值被清除,可使用 --append 參數(shù)
此命令有以下三個(gè)參數(shù):
–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博客 ,轉(zhuǎn)載時(shí)請(qǐng)注明出處及相應(yīng)鏈接。
更多關(guān)于PHP框架相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》,《codeigniter入門(mén)教程》,《CI(CodeIgniter)框架進(jìn)階教程》,《Yii框架入門(mén)及常用技巧總結(jié)》及《ThinkPHP入門(mén)教程》
希望本文所述對(duì)大家基于Symfony框架的PHP程序設(shè)計(jì)有所幫助。
- Symfony數(shù)據(jù)校驗(yàn)方法實(shí)例分析
- 如何在symfony中導(dǎo)出為CSV文件中的數(shù)據(jù)
- Symfony2實(shí)現(xiàn)在controller中獲取url的方法
- Symfony2框架學(xué)習(xí)筆記之表單用法詳解
- Symfony2學(xué)習(xí)筆記之系統(tǒng)路由詳解
- Symfony2學(xué)習(xí)筆記之控制器用法詳解
- Symfony2學(xué)習(xí)筆記之模板用法詳解
- Symfony2安裝第三方Bundles實(shí)例詳解
- Symfony2 session用法實(shí)例分析
- 高性能PHP框架Symfony2經(jīng)典入門(mén)教程
- Symfony2實(shí)現(xiàn)從數(shù)據(jù)庫(kù)獲取數(shù)據(jù)的方法小結(jié)

