国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

CodeIgniter下引入ORMDoctrine

2019-11-14 14:43:29
字體:
供稿:網(wǎng)友

做了兩年的CI開發(fā),一直使用activeRecord來操作數(shù)據(jù)庫。簡單,輕巧加方便。最近一個項目交給手下去做,也是采用從數(shù)據(jù)庫設(shè)計入手的開發(fā)流程,現(xiàn)在已經(jīng)上線運行。經(jīng)歷了理清需求,設(shè)計數(shù)據(jù)庫,在CI中建立model, controller,需求變更,更改數(shù)據(jù)庫,更改代碼,增加需求,更改數(shù)據(jù)庫等過程。回頭來看,當(dāng)需要了解全局代碼和業(yè)務(wù)邏輯需求時,還是得從數(shù)據(jù)庫入手,突然有一種厭煩的感腳:對象的屬性都在數(shù)據(jù)庫里,而相關(guān)的操作在代碼中,覺得很分裂。回想多年前開發(fā)的C#與java中都有一些好用的ORM的框架,對我來說,ORM最大的好處是隱藏數(shù)據(jù)庫,項目前期設(shè)計時根據(jù)需求來設(shè)計對象,輕裝上陣,不必早早地陷入增改刪查中;直接利用工具將對象映射到數(shù)據(jù)庫中;數(shù)據(jù)庫的增改刪查也都是面向?qū)ο蟮摹?/span>

可能存在的兩點顧慮:

  1. 既然要由對象自動映射到數(shù)據(jù)庫,自然要遵守一套metaData規(guī)則才行。
  2. 性能問題,由ORM自動生成sql語句,性能可能不如以前。但對比框架的可讀性/可維護性與少許的硬件性能成本,還是選擇框架優(yōu)先。另外,相信ORM的90%的性能影響不大,少許的實在ORM解決不了的問題也能提供原生的sql來解決,總體來說,是利大于弊。

(官方參考文檔:http://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html

開始吧,我們的目的是什么,沒有蛀牙!好吧,這只是我們的一個目的,還在其它的目的:

  • 根據(jù)建立的對象生成數(shù)據(jù)庫;
  • 新增對象持久化到數(shù)據(jù)庫中;
  • 能使用entity來方便查詢數(shù)據(jù)里的信息并達到更改。

1. 在CI下安裝doctrine

     a. 最新的CI 3.0已支持composer。application文件夾下建立composer.son文件如下。(不是在CI根目錄下)。 注意autoload參數(shù)(不是官方例子中的/src/文件夾) 

          

{    "require": {        "doctrine/orm": "2.4.*",        "symfony/yaml": "2.*"    },    "autoload": {        "psr-0": {"": "models/entities"}    }}

 

notes: 上面autoload參數(shù)很重要,因為doctrine的啟動需要指明entity目錄,原始例子中給定的是/src,這里我們放在CI的model/entities目錄下,另外,同時創(chuàng)建model/generated 與 models/PRoxies目錄,generated目錄用來由數(shù)據(jù)庫生成entity,proxies目錄用來存放lazy load需要生成的代碼.

     b. 安裝doctrine: composer install. 安裝后目錄結(jié)構(gòu)如下:

      

2. 配置bootstrap與cli-config

在doctrine中,bootstrap負(fù)責(zé)創(chuàng)建entityManager,entityManager是整個doctrine對外提供的操作接口: 隱藏數(shù)據(jù)庫接口,提供了對entity的查詢,更新及持久化。

在bootstrap中,首先使用composer自帶的功能對整個doctrine實現(xiàn)加載。(這里保留了composer功能,實現(xiàn)將doctrine引入到CI修改最小化)

創(chuàng)建基本的entityManager只需要兩步:

  1. 使用setup創(chuàng)建config。
  2. 初始化數(shù)據(jù)庫配置對象。

使用數(shù)據(jù)庫連接對象創(chuàng)建entityManager后我們可能及不可耐就想用來從對象來逆向工程數(shù)據(jù)庫了。別急,慢慢來。

 

<?php// bootstrap.phpuse Doctrine/ORM/Tools/Setup;use Doctrine/ORM/EntityManager;use Doctrine/Common/ClassLoader,    Doctrine/DBAL/Logging/EchoSQLLogger,    Doctrine/Common/Cache/ArrayCache;date_default_timezone_set("Asia/Shanghai");require_once "vendor/autoload.php";// database configuration parametersif(defined(APPPATH)){    require_once APPPATH.'config/database.php';    $conn = array(            'driver' => 'pdo_MySQL',            'user' =>     $db['default']['username'],            'passWord' => $db['default']['password'],            'host' =>     $db['default']['hostname'],            'dbname' =>   $db['default']['database']        );}else{    $conn = array(    'driver' => 'pdo_mysql',    'user' =>     'root',    'password' => '',    'host' =>     '127.0.0.1',    'dbname' =>   'doctrine');}//Below can be exected in cli/*require_once APPPATH.'vendor/Doctrine/Common/lib/doctrine/common/ClassLoader.php';$doctrineClassLoader = new ClassLoader('Doctrine',  APPPATH.'libraries');$doctrineClassLoader->register();$entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/" ));$entitiesClassLoader->register();$proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies');$proxiesClassLoader->register();*/// Create a simple "default" Doctrine ORM configuration for Annotations$isDevMode = true;$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/models/entities"), $isDevMode);// or if you prefer yaml or xml//$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);//$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yaml"), $isDevMode);$cache = new ArrayCache;$config->setMetadataCacheImpl($cache);$driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__.'/models/entities'));$config->setMetadataDriverImpl($driverImpl);$config->setQueryCacheImpl($cache);$config->setQueryCacheImpl($cache);// Proxy configuration$config->setProxyDir(__DIR__.'/models/proxies');$config->setProxyNamespace('Proxies');// Set up logger//$logger = new EchoSQLLogger;//$config->setSQLLogger($logger);$config->setAutoGenerateProxyClasses( TRUE );// obtaining the entity managerglobal $entityManager;$entityManager = EntityManager::create($conn, $config);
View Code

 

要讓entityManager知道用哪里的對象來進行反向工程,下面這句就尤為重要了:

$config = SetupcreateAnnotationMetadataConfiguration(array(DIR."/models/entities"), $isDevMode);

(在這里也提一下,當(dāng)從數(shù)據(jù)庫生成entity時當(dāng)然也要指明entity要放在哪個文件夾了,使用的是EntityGenerator對象,使用該對象的generate方法時指定存放的文件夾就可以了。)

官方文檔中使用的是命令行的方法來進行反向工程的,我們這里也依樣畫葫蘆,接下來創(chuàng)建必要的cli-config文件。這個文件相對來講就沒有bootstrap那么長了,總公只有下面兩行即可:

 

requireonce "bootstrap.php";return DoctrineORMToolsConsoleConsoleRunnercreateHelperSet($entityManager);

 

反向工程使用vendor/bin/中的doctrine命令:

 

vendor/bin/doctrine

 

其中常用的有如下:

 

vendor/bin/doctrine orm:schema-tool:createvendor/bin/doctrine orm:schema-tool:update --force

 

notes: 使用update命令新增字段不會影響原先的數(shù)據(jù)。

 

好吧,是不是急不可奈要試一試了,輸入第一條create命令,咦,不好出現(xiàn)一個錯誤 “No Metadata Classes to process.” ,心跳加快,冷靜,這是正常的,是因為我們還沒建立我們想要的entity呢。

建立entity進行反向工程

     1. 在/models/entities中建立我們第一個entity: Product.php

          注意這里的每一個屬性都protected屬性,對應(yīng)都有一對mutator(getter與setter)這是有什么用處的呢?由官方文檔所說是用來方便doctrine來產(chǎn)生entity,而不是使用entity.field=foo的方式。具體在doctrine如何操作的有待進一步探索。對于主鍵Id是沒有setter方法的,你懂的。

     2. 現(xiàn)在我們只是定義了對象,但數(shù)據(jù)庫構(gòu)造是需要一些數(shù)據(jù)庫屬性的,類名與屬性前面的metadata就是來干這個的。(定義的表名,對象屬性對應(yīng)的數(shù)據(jù)庫字段名與字段屬性)

 

<?php// src/Product.php/** * @Entity @Table(name="products") **/class Product{    /** @Id @Column(type="integer") @GeneratedValue **/    protected $id;        /** @Column(type="string") **/    protected $name;    public function getId()    {        return $this->id;    }    public function getName()    {        return $this->name;    }    public function setName($name)    {        $this->name = $name;    }}

 

     3. 下面我們就可以使用下面命令來進行反向工程了,是不是很興奮!

          

vendor/bin/doctrine orm:schema-tool:update --force --dump-sql

 

     4. 下面我們就來建立一段腳本來生成一個product并將其插入數(shù)據(jù)(持久化),你就會發(fā)現(xiàn)如何面向?qū)ο螅[藏數(shù)據(jù)庫操作的了。

  1. <?php require_once "bootstrap.php";$newProductName = $argv[1];$product = new Product();$product->setName($newProductName);$entityManager->persist($product);$entityManager->flush();echo "Created Product with ID " . $product->getId() . "/n";

     5. 下面我們就要使用cli來運行這段php腳本調(diào)用ORM框架來插入product了。

  1. $ php createproduct.php ORM $ php createproduct.php DBAL

查看數(shù)據(jù)庫,是不是發(fā)現(xiàn)了新的數(shù)據(jù)已經(jīng)插入了,ok大功告成。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 于都县| 黎平县| 建昌县| 常山县| 冷水江市| 繁峙县| 新野县| 梓潼县| 昂仁县| 西吉县| 观塘区| 腾冲县| 彭州市| 项城市| 常熟市| 嘉义市| 牟定县| 鹤壁市| 鹰潭市| 凤庆县| 东乡族自治县| 南昌市| 兴义市| 乐亭县| 若羌县| 太原市| 定州市| 平利县| 泸水县| 遵义县| 汉寿县| 尚义县| 仁寿县| 北辰区| 潜江市| 安阳市| 彭泽县| 平顺县| 紫云| 疏勒县| 雅江县|