使用doctrine codeigniter获取记录

时间:2017-12-22 13:40:20

标签: php codeigniter doctrine-orm

我已经整合了学说ORM和codeigniter(都有最新版本)
mysql表实体也是由doctrine创建的 但是没有使用学说实体从数据库中获取数据的知识 我用下面的结构来整合学说和代码签名 https://github.com/pedrozok/codeigniter-doctrine-bootstrap
我修改了doctrine库,如下所示。

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

use Doctrine\Common\ClassLoader,
    Doctrine\ORM\Tools\Setup,
    Doctrine\ORM\EntityManager,
    Doctrine\ORM\Mapping\Driver\DatabaseDriver,
    Doctrine\ORM\Tools\DisconnectedClassMetadataFactory,
    Doctrine\ORM\Tools\EntityGenerator,
    Doctrine\Common\Cache\ApcCache;

class Doctrine {

    public $em;

    public function __construct() {
        require_once __DIR__ . '/Doctrine/ORM/Tools/Setup.php';
        Setup::registerAutoloadDirectory(__DIR__);

        if (!file_exists($file_path = APPPATH . 'config/' . ENVIRONMENT . '/database.php') && !file_exists($file_path = APPPATH . 'config/database.php')) {
            throw new Exception('The configuration file database.php does not exist.');
        }
        require $file_path;

        $connection_options = array(
            'driver' => 'pdo_mysql',
            'user' => $db['default']['username'],
            'password' => $db['default']['password'],
            'host' => $db['default']['hostname'],
            'dbname' => $db['default']['database'],
            'charset' => $db['default']['char_set'],
            'driverOptions' => array(
                'charset' => $db['default']['char_set'],
            ),
        );

        // With this configuration, your model files need to be in application/models/Entity
        // e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
        $models_namespace = 'Entity';
        $models_path = APPPATH . 'models';
        $proxies_dir = APPPATH . 'models/Proxies';
        $metadata_paths = array(APPPATH . 'models');
        $extension_dir = APPPATH . 'libraries/Doctrine';

        // Set $dev_mode to TRUE to disable caching while you develop
        $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies_dir);

        // Proxy configuration
        $config->setProxyDir(APPPATH . '/models/proxies');
        $config->setProxyNamespace('Proxies');

        $this->em = EntityManager::create($connection_options, $config);
        /* code added to handle enum datatype starts here */
        $platform = $this->em->getConnection()->getDatabasePlatform();
        $platform->registerDoctrineTypeMapping('enum', 'string');
        /* ends enum code */

        $loader = new ClassLoader($models_namespace, $models_path);
        $loader->register();
        /**
         * generate entities from database
         * @return none
         */
        // $this->generate_doctrine_entities($this->em, APPPATH . "models/Entity");
        /* ends */
        //$this->create_update_database($this->em, "update");
    }

    function generate_doctrine_entities($em, $path) {

        $em->getConfiguration()->setMetadataDriverImpl(
                new DatabaseDriver($this->em->getConnection()->getSchemaManager())
        );

        $cmf = new DisconnectedClassMetadataFactory();
        $cmf->setEntityManager($em);
        $metadata = $cmf->getAllMetadata();
        $generator = new EntityGenerator();
        $generator->setRegenerateEntityIfExists(false);
        $generator->setUpdateEntityIfExists(true);
        $generator->setGenerateStubMethods(true);
        $generator->setGenerateAnnotations(true);
        $generator->generate($metadata, $path);
    }

    function create_update_database($em, $mode = "update") {

        $tool = new \Doctrine\ORM\Tools\SchemaTool($em);

        $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
        $cmf->setEntityManager($em);
        $metadata = $cmf->getAllMetadata();

        if ($mode == "create") {
            $queries = $tool->getCreateSchemaSql($metadata);
        } else {
            $queries = $tool->getUpdateSchemaSql($metadata);
        }
        echo "Total queries: " . count($queries) . "<br /><br />";
        for ($i = 0; $i < count($queries); $i++) {
            $em->getConnection()->prepare($queries[$i])->execute();
            echo $queries[$i] . "<br /><br />Execution Successful: " . ($i + 1) . "<br /><br />";
        }
    }

}

是否有任何建议将doctrine实体包含在codeigniter模型中并从实体获取数据?

1 个答案:

答案 0 :(得分:0)

以下是一些代码示例对您有帮助吗?

// Fetch data by Native SQL
// $em is entity manager
$sql = "SELECT * FROM userView ";
// $em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
  \Doctrine\Common\Util\Debug::dump( $stmt->fetchAll() );

//fetching data in by DQL
$qb = $em->getRepository('User')->createQueryBuilder('u');
//$qb->andWhere('u.id = :id')->setParameter('id', $id);
$data = $qb->getQuery()->getResult( ); // in objects

$data = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY); // in array

 echo '<pre>'; \Doctrine\Common\Util\Debug::dump($data);
// Fetching data by common way
$data = $em->getRepository('User');
$datax = $data->findAll();

foreach($datax as $d) {
  echo '<pre>'; \Doctrine\Common\Util\Debug::dump($d);