cxzlr 发表于 2013-2-26 10:45:05

CI2整合Doctrine2的小例子,喜欢就看看吧

本帖最后由 cxzlr 于 2013-2-26 10:56 编辑

希望大家共同研究一下,他吧,这东西配合CI真不错呀,偶刚看了一下,分享一下。
1.当然是下载doctrine 包了,下载后放到application/libraries 下,目录结构如下
http://image.22kk.com/themes/upfile/upattachment/2013-02-26/201302261022557847.jpg
2. 在 Doctrine/ 创建一个文件名为Doctrine.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
http://image.22kk.com/themes/upfile/upattachment/2013-02-26/201302261029026624.jpg

Article.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
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
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 的内容如下

Entities\Article:
type: entity
table: articles
fields:
    id:
      type: integer
      id: true
      generator:
      strategy: AUTO
    title:
      type: string
      length: 255
      nullable: false
    content:
      type: text
      nullable: false
    created:
      type: datetime
      nullable: false
manyToOne:
    user:
      targetEntity: User
      joinColumns:
      user_id:
          referencedColumnName: id


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

Entities\Test:
type: entity
table: test
fields:
    id:
      type: integer
      id: true
      generator:
      strategy: AUTO
    title:
      type: string
      length: 255
      nullable: false
    content:
      type: text
      nullable: false
    created:
      type: datetime
      nullable: false
oneToOne:
    user:
      targetEntity: User
      joinColumns:
      user_id:
          referencedColumnName: id


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

Entities\User:
type: entity
table: users
uniqueConstraints:
    email_index:
      columns:
      - email
fields:
    id:
      type: integer
      id: true
      generator:
      strategy: AUTO
    password:
      type: string
      length: 32
      nullable: false
    firstName:
      type: string
      length: 255
      nullable: false
      column: first_name
    lastName:
      type: string
      length: 255
      nullable: false
      column: last_name
    email:
      type: string
      length: 255
      nullable: false
    website:
      type: string
      length: 255
      nullable: true
    created:
      type: datetime
      nullable: false


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


--
-- 表的结构 `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=InnoDBDEFAULT 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=InnoDBDEFAULT 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.控制器里的代码

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.com');
    $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);
}
}


cxzlr 发表于 2013-2-26 11:03:32

大家注意了,这要PHP5.3 以上的版本哟。希望有高手懂的多发点关于这方面的资料,CI官网是不是也推出一些这方面的资料呀,为了共同的目标少写,增优同志们,分享你们的知识吧。

创业论坛 发表于 2013-2-27 17:32:18

呵呵,不错的例子,学习了

阿程 发表于 2013-6-21 15:54:36

很好 yml文件多了个\

mckee1990 发表于 2013-6-25 15:22:19

怎么自动生成yml 和Entities不会手动吧

Icen 发表于 2014-5-19 16:53:28

不明白啊,哪里还有教程啊?

feimengv 发表于 2014-5-20 15:02:50

是干嘛用的?

newcmd 发表于 2016-10-6 22:58:44

目录结构图看不到啊
页: [1]
查看完整版本: CI2整合Doctrine2的小例子,喜欢就看看吧