用户
 找回密码
 入住 CI 中国社区
搜索
查看: 8533|回复: 7
收起左侧

[数据库] CI2整合Doctrine2的小例子,喜欢就看看吧

[复制链接]
发表于 2013-2-26 10:45:05 | 显示全部楼层 |阅读模式
本帖最后由 cxzlr 于 2013-2-26 10:56 编辑

希望大家共同研究一下,他吧,这东西配合CI真不错呀,偶刚看了一下,分享一下。
1.当然是下载doctrine 包了,下载后放到application/libraries 下,目录结构如下

2. 在 Doctrine/ 创建一个文件名为Doctrine.php ,内容如下
PHP复制代码
 
class Doctrine
{
    // the Doctrine entity manager
    public $em = null;
    public function __construct()
    {
        // include our CodeIgniter application's database configuration
        require_once APPPATH.'config/database.php';
       
        // include Doctrine's fancy ClassLoader class
        require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';
        // load the Doctrine classes
        $doctrineClassLoader = new \Doctrine\Common\ClassLoader('Doctrine', APPPATH.'libraries');
        $doctrineClassLoader->register();
       
        // load Symfony2 helpers
        // Don't be alarmed, this is necessary for YAML mapping files
        $symfonyClassLoader = new \Doctrine\Common\ClassLoader('Symfony', APPPATH.'libraries/Doctrine');
        $symfonyClassLoader->register();
        // load the entities
        $entityClassLoader = new \Doctrine\Common\ClassLoader('Entities', APPPATH.'models');
        $entityClassLoader->register();
        // load the proxy entities
        $proxyClassLoader = new \Doctrine\Common\ClassLoader('Proxies', APPPATH.'models');
        $proxyClassLoader->register();
        // set up the configuration
        $config = new \Doctrine\ORM\Configuration;
   
        if(ENVIRONMENT == 'development')
            // set up simple array caching for development mode
            $cache = new \Doctrine\Common\Cache\ArrayCache;
        else
            // set up caching with APC for production mode
            $cache = new \Doctrine\Common\Cache\ApcCache;
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);
        // set up proxy configuration
        $config->setProxyDir(APPPATH.'models/Proxies');
        $config->setProxyNamespace('Proxies');
       
        // auto-generate proxy classes if we are in development mode
        $config->setAutoGenerateProxyClasses(ENVIRONMENT == 'development');
        // set up annotation driver
        $yamlDriver = new \Doctrine\ORM\Mapping\Driver\YamlDriver(APPPATH.'models/Mappings');
        $config->setMetadataDriverImpl($yamlDriver);
        // Database connection information
        $connectionOptions = array(
            'driver' => 'pdo_mysql',
            'user' => $db['default']['username'],
            'password' => $db['default']['password'],
            'host' => $db['default']['hostname'],
            'dbname' => $db['default']['database'],
         'charset' => 'utf8',
         'driverOptions' => array(1002=>'SET NAMES utf8')
        );
       
        // create the EntityManager
        $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
       
        // store it as a member, for use in our CodeIgniter controllers.
        $this->em = $em;
    }
}
 
复制代码

3.在application/models/ 创建目录Entities(实体)、Mappings(关系描述)、Proxies


Article.php 内容如下
PHP复制代码
 
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Article
*/

class Article
{
    /**
     * @var integer
     */

    private $id;
    /**
     * @var string
     */

    private $title;
    /**
     * @var string
     */

    private $content;
    /**
     * @var \DateTime
     */

    private $created;
    /**
     * @var \Entities\User
     */

    private $user;
 
    /**
     * Get id
     *
     * @return integer
     */

    public function getId()
    {
        return $this->id;
    }
    /**
     * Set title
     *
     * @param string $title
     * @return Article
     */

    public function setTitle($title)
    {
        $this->title = $title;
   
        return $this;
    }
    /**
     * Get title
     *
     * @return string
     */

    public function getTitle()
    {
        return $this->title;
    }
    /**
     * Set content
     *
     * @param string $content
     * @return Article
     */

    public function setContent($content)
    {
        $this->content = $content;
   
        return $this;
    }
    /**
     * Get content
     *
     * @return string
     */

    public function getContent()
    {
        return $this->content;
    }
    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Article
     */

    public function setCreated($created)
    {
        $this->created = $created;
   
        return $this;
    }
    /**
     * Get created
     *
     * @return \DateTime
     */

    public function getCreated()
    {
        return $this->created;
    }
    /**
     * Set user
     *
     * @param \Entities\User $user
     * @return Article
     */

    public function setUser(\Entities\User $user = null)
    {
        $this->user = $user;
   
        return $this;
    }
    /**
     * Get user
     *
     * @return \Entities\User
     */

    public function getUser()
    {
        return $this->user;
    }
}
 
 
复制代码

Test.php内容如下
PHP复制代码
 
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Test
*/

class Test
{
    /**
     * @var integer
     */

    private $id;
    /**
     * @var string
     */

    private $title;
    /**
     * @var string
     */

    private $content;
    /**
     * @var \DateTime
     */

    private $created;
    /**
     * @var \Entities\User
     */

    private $user;
 
    /**
     * Get id
     *
     * @return integer
     */

    public function getId()
    {
        return $this->id;
    }
    /**
     * Set title
     *
     * @param string $title
     * @return Test
     */

    public function setTitle($title)
    {
        $this->title = $title;
   
        return $this;
    }
    /**
     * Get title
     *
     * @return string
     */

    public function getTitle()
    {
        return $this->title;
    }
    /**
     * Set content
     *
     * @param string $content
     * @return Test
     */

    public function setContent($content)
    {
        $this->content = $content;
   
        return $this;
    }
    /**
     * Get content
     *
     * @return string
     */

    public function getContent()
    {
        return $this->content;
    }
    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Test
     */

    public function setCreated($created)
    {
        $this->created = $created;
   
        return $this;
    }
    /**
     * Get created
     *
     * @return \DateTime
     */

    public function getCreated()
    {
        return $this->created;
    }
    /**
     * Set user
     *
     * @param \Entities\User $user
     * @return Test
     */

    public function setUser(\Entities\User $user = null)
    {
        $this->user = $user;
   
        return $this;
    }
    /**
     * Get user
     *
     * @return \Entities\User
     */

    public function getUser()
    {
        return $this->user;
    }
}
 
复制代码

User.php内容如下
PHP复制代码
 
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*/

class User
{
    /**
     * @var integer
     */

    private $id;
    /**
     * @var string
     */

    private $password;
    /**
     * @var string
     */

    private $firstName;
    /**
     * @var string
     */

    private $lastName;
    /**
     * @var string
     */

    private $email;
    /**
     * @var string
     */

    private $website;
    /**
     * @var \DateTime
     */

    private $created;
 
    /**
     * Get id
     *
     * @return integer
     */

    public function getId()
    {
        return $this->id;
    }
    /**
     * Set password
     *
     * @param string $password
     * @return User
     */

    public function setPassword($password)
    {
        $this->password = $password;
   
        return $this;
    }
    /**
     * Get password
     *
     * @return string
     */

    public function getPassword()
    {
        return $this->password;
    }
    /**
     * Set firstName
     *
     * @param string $firstName
     * @return User
     */

    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
   
        return $this;
    }
    /**
     * Get firstName
     *
     * @return string
     */

    public function getFirstName()
    {
        return $this->firstName;
    }
    /**
     * Set lastName
     *
     * @param string $lastName
     * @return User
     */

    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
   
        return $this;
    }
    /**
     * Get lastName
     *
     * @return string
     */

    public function getLastName()
    {
        return $this->lastName;
    }
    /**
     * Set email
     *
     * @param string $email
     * @return User
     */

    public function setEmail($email)
    {
        $this->email = $email;
   
        return $this;
    }
    /**
     * Get email
     *
     * @return string
     */

    public function getEmail()
    {
        return $this->email;
    }
    /**
     * Set website
     *
     * @param string $website
     * @return User
     */

    public function setWebsite($website)
    {
        $this->website = $website;
   
        return $this;
    }
    /**
     * Get website
     *
     * @return string
     */

    public function getWebsite()
    {
        return $this->website;
    }
    /**
     * Set created
     *
     * @param \DateTime $created
     * @return User
     */

    public function setCreated($created)
    {
        $this->created = $created;
   
        return $this;
    }
    /**
     * Get created
     *
     * @return \DateTime
     */

    public function getCreated()
    {
        return $this->created;
    }
}
 
复制代码


Entities.Article.dcm.yml 的内容如下

  1. Entities\Article:
  2.   type: entity
  3.   table: articles
  4.   fields:
  5.     id:
  6.       type: integer
  7.       id: true
  8.       generator:
  9.         strategy: AUTO
  10.     title:
  11.       type: string
  12.       length: 255
  13.       nullable: false
  14.     content:
  15.       type: text
  16.       nullable: false
  17.     created:
  18.       type: datetime
  19.       nullable: false
  20.   manyToOne:
  21.     user:
  22.       targetEntity: User
  23.       joinColumns:
  24.         user_id:
  25.           referencedColumnName: id
复制代码


Entities.Test.dcm.yml 的内容如下

  1. Entities\Test:
  2.   type: entity
  3.   table: test
  4.   fields:
  5.     id:
  6.       type: integer
  7.       id: true
  8.       generator:
  9.         strategy: AUTO
  10.     title:
  11.       type: string
  12.       length: 255
  13.       nullable: false
  14.     content:
  15.       type: text
  16.       nullable: false
  17.     created:
  18.       type: datetime
  19.       nullable: false
  20.   oneToOne:
  21.     user:
  22.       targetEntity: User
  23.       joinColumns:
  24.         user_id:
  25.           referencedColumnName: id
复制代码


Entities.User.dcm.yml 文件的内容如下

  1. Entities\User:
  2.   type: entity
  3.   table: users
  4.   uniqueConstraints:
  5.     email_index:
  6.       columns:
  7.         - email
  8.   fields:
  9.     id:
  10.       type: integer
  11.       id: true
  12.       generator:
  13.         strategy: AUTO
  14.     password:
  15.       type: string
  16.       length: 32
  17.       nullable: false
  18.     firstName:
  19.       type: string
  20.       length: 255
  21.       nullable: false
  22.       column: first_name
  23.     lastName:
  24.       type: string
  25.       length: 255
  26.       nullable: false
  27.       column: last_name
  28.     email:
  29.       type: string
  30.       length: 255
  31.       nullable: false
  32.     website:
  33.       type: string
  34.       length: 255
  35.       nullable: true
  36.     created:
  37.       type: datetime
  38.       nullable: false
复制代码


4.创建数据库表结构  (注意了  ENGINE=InnoDB   了,要用到外键)

SQL复制代码
 
--
-- 表的结构 `articles`
--
CREATE TABLE IF NOT EXISTS `articles` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `user_id` INT(11) DEFAULT NULL,
  `title` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
  `content` longtext COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_BFDD3168A76ED395` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;
-- --------------------------------------------------------
--
-- 表的结构 `test`
--
CREATE TABLE IF NOT EXISTS `test` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `user_id` INT(11) DEFAULT NULL,
  `title` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
  `content` longtext COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UNIQ_D87F7E0CA76ED395` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- 表的结构 `users`
--
CREATE TABLE IF NOT EXISTS `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `password` VARCHAR(32) COLLATE utf8_unicode_ci NOT NULL,
  `first_name` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
  `website` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email_index` (`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;
--
-- 限制导出的表
--
--
-- 限制表 `articles`
--
ALTER TABLE `articles`
  ADD CONSTRAINT `FK_BFDD3168A76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- 限制表 `test`
--
ALTER TABLE `test`
  ADD CONSTRAINT `FK_D87F7E0CA76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
 
 
复制代码

5.控制器里的代码
PHP复制代码
 
class Welcome extends CI_Controller {
/**
  * test Page for this controller.  *
   */

public function index()
{
   $this->load->library('Doctrine');
   $user = new Entities\User;
    $user->setFirstName('xuezheng.chang');
    $user->setLastName('cxzlr');
    $user->setPassword(md5('cxzlr'));
    $user->setEmail('xuezheng.chang@hotmail[url=mailto:].com'[/url]);
    $user->setWebsite('http://test.com');
    $user->setCreated(new DateTime());
   
    // standard way in CodeIgniter to access a library in a controller: $this->library_name->member->memberFunction()
    // save the object to database, so that it can obtain its ID
    $this->doctrine->em->persist($user);
   
    // create a new article object
    $article = new Entities\Article;
    $article->setTitle('2Emma Watson is extremely talented, no?');
    $article->setContent('2By talented, I mean good at lookin\' good.');
    $article->setCreated(new DateTime());
    // the user object you pass must be persisted first!
    $article->setUser($user);
   
    // save the article object to the database
    $this->doctrine->em->persist($article);
    $this->doctrine->em->flush();
   
   
$article = $this->doctrine->em->find('Entities\Article', 1);
   
   print_r($article);
}
}
 
 
复制代码

 楼主| 发表于 2013-2-26 11:03:32 | 显示全部楼层
大家注意了,这要PHP5.3 以上的版本哟。希望有高手懂的多发点关于这方面的资料,CI官网是不是也推出一些这方面的资料呀,为了共同的目标少写,增优同志们,分享你们的知识吧。
发表于 2013-2-27 17:32:18 | 显示全部楼层
呵呵,不错的例子,学习了
发表于 2013-6-21 15:54:36 | 显示全部楼层
很好 yml文件多了个\  
发表于 2013-6-25 15:22:19 | 显示全部楼层
怎么自动生成yml 和  Entities  不会手动吧
发表于 2014-5-19 16:53:28 | 显示全部楼层
不明白啊,哪里还有教程啊?
发表于 2014-5-20 15:02:50 | 显示全部楼层
是干嘛用的?
发表于 2016-10-6 22:58:44 | 显示全部楼层
目录结构图看不到啊

本版积分规则