php - 如何使用条令命令实用程序从数据库生成实体?

标签 php codeigniter doctrine-orm

我已经成功地将 doctrine 安装到我的 Codeigniter 项目中。 现在我遇到了一个问题,我无法与我的数据库通信以从中生成我的实体。

来 self 的 codeigniter application/libraries/Doctrine.php

<?php
use Doctrine\Common\ClassLoader,
    Doctrine\ORM\Configuration,
    Doctrine\ORM\EntityManager,
    Doctrine\Common\Cache\ArrayCache,
    Doctrine\DBAL\Logging\EchoSQLLogger;



/**
*
* How to create advanced configurations
* http://docs.doctrine-project.org/en/2.0.x/reference/configuration.html
*
**/

class Doctrine {

  public $em = null;

  public function __construct()
  {

    if (!defined('APPPATH')){
        define('APPPATH', 'application/');
    }

    // load database configuration from CodeIgniter
    require_once APPPATH.'config/database.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();

    //Set up caches
    $config = new Configuration;
    $cache = new ArrayCache;
    $config->setMetadataCacheImpl($cache);
    $driverImpl = $config->newDefaultAnnotationDriver(array(APPPATH.'models/Entities'));
    $config->setMetadataDriverImpl($driverImpl);
    $config->setQueryCacheImpl($cache);

    // Proxy configuration
    // Sets the directory where Doctrine generates any necessary proxy class files.
    $config->setProxyDir(APPPATH.'/models/proxies');
    $config->setProxyNamespace('Proxies');

    // Set up logger
    $logger = new EchoSQLLogger;
    $config->setSQLLogger($logger);

    $config->setAutoGenerateProxyClasses( TRUE );

    // Database connection information


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

    // Create EntityManager
    $this->em = EntityManager::create($connectionOptions, $config);
  }
}

来 self 的`application/config/database.php

$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = '127.0.0.1';
$db['default']['username'] = 'root';
$db['default']['password'] = 'root';
$db['default']['database'] = 'Inbox';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

来 self 的application/cli-config.php

<?php

//  You are missing a "cli-config.php" or "config/cli-config.php" file in your
// project, which is required to get the Doctrine Console working. You can use the
// following sample as a template:

use Doctrine\ORM\Tools\Console\ConsoleRunner;

define('BASEPATH', APPPATH . '/../system/');
// replace with file to your own project bootstrap
require __DIR__ . '/application/libraries/Doctrine.php';

// replace with mechanism to retrieve EntityManager in your app
$entity = new Doctrine();

$doctrine = new Doctrine;
$em = $doctrine->em;

$helperSet = new Symfony\Component\Console\Helper\HelperSet(array(
    'db' => new Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
    'em' => new Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));

\Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet);

Doctrine 是通过 Composer 安装的。 所以我的应用程序文件结构如下所示:

{root}
--application/
-----libraries/
---------Doctrine.php
--system/
--vendor/
-----bin/
---------doctrine   <-------- this is the command line utility
---------doctrine.php
-----composer/
-----doctrine/
-----symfony/
-----autoload.php
--index.php

autoload.php 当前正在加载到 index.php 该文件的底部如下所示:

/*
 * --------------------------------------------------------------------
 * LOAD COMPOSER CLASSES
 * --------------------------------------------------------------------
 */
include_once 'vendor/autoload.php';



/*
 * --------------------------------------------------------------------
 * LOAD THE BOOTSTRAP FILE
 * --------------------------------------------------------------------
 *
 * And away we go...
 *
 */
require_once BASEPATH.'core/CodeIgniter.php';

/* End of file index.php */
/* Location: ./index.php */

为了我自己的方便,我将 Doctrine 添加到 application/config/autoload.php 这样我就可以像这样从我的 Controller 访问学说:

class Welcome extends CI_Controller {

    public function index()
    {
        echo "<pre>";
        print_r($this->doctrine->em);  
            //the line above Prints the EntityManager created by Doctrine Library
            //with this line -> $this->em = EntityManager::create($connectionOptions, $config);
            echo "</pre>";          

        $this->load->view('welcome_message');
    }
}

从上面的 print_r 的输出中,我可以看到在我第一次创建 EntityManager 连接时分配了哪些数据库设置

[_expr:protected] => Doctrine\DBAL\Query\Expression\ExpressionBuilder Object
                (
                    [connection:Doctrine\DBAL\Query\Expression\ExpressionBuilder:private] => Doctrine\DBAL\Connection Object
 *RECURSION*
                )

            [_isConnected:Doctrine\DBAL\Connection:private] => 
            [_transactionNestingLevel:Doctrine\DBAL\Connection:private] => 0
            [_transactionIsolationLevel:Doctrine\DBAL\Connection:private] => 2
            [_nestTransactionsWithSavepoints:Doctrine\DBAL\Connection:private] => 
            [_params:Doctrine\DBAL\Connection:private] => Array
                (
                    [driver] => pdo_mysql
                    [user] => root
                    [password] => root
                    [host] => 127.0.0.1
                    [dbname] => Inbox
                )

            [_platform:protected] => Doctrine\DBAL\Platforms\MySqlPlatform Object
                (
                    [doctrineTypeMapping:protected] => 
                    [doctrineTypeComments:protected] => 
                    [_eventManager:protected] => Doctrine\Common\EventManager Object
                        (
                            [_listeners:Doctrine\Common\EventManager:private] => Array
                                (
                                )

                        )

                    [_keywords:protected] => 
                )

            [_schemaManager:protected] => 
            [_driver:protected] => Doctrine\DBAL\Driver\PDOMySql\Driver Object
                (
                )

            [_isRollbackOnly:Doctrine\DBAL\Connection:private] => 
            [defaultFetchMode:protected] => 2
        )

那么问题来了。 正确安装所有内容后,我确实打开了终端并导航到我的 codeigniter 项目的根目录。从那里我输入:

php vendor/bin/doctrine orm:convert-mapping --from-database annotation application/models

根据帮助函数,这是语法

orm:convert-mapping [--filter="..."] [--force] [--from-database] [--extend[="..."]] [--num-spaces[="..."]] [--namespace[="..."]] to-type dest-path

这是我在终端上打印的内容:

**[Doctrine\DBAL\DBALException]**                                                              
  An exception occurred while executing 'SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'':  

  SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected    

**[PDOException]**                                                    
  SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

我很沮丧。有人可以帮助我吗?

最佳答案

$db['default']['username'] = 'root';
$db['default']['password'] = '';

因为本地主机的默认密码为空

关于php - 如何使用条令命令实用程序从数据库生成实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487981/

相关文章:

php - 传递变量引用的问题

php - codeigniter 缓存总是返回空

php - 使用 createNativeQuery 连接两个没有外键的实体

php - 在模型中调用多个方法或在 Controller 、CodeIgniter 中调用?

php - 谁能告诉我 paypal 按钮之间的区别

html - 我如何移动 div 使它们不重叠

php - 如何扩展 FOSUserBundle 的用户实体?

php - Zend_Paginator/Doctrine 2

javascript - ajax 请求在 localhost wampserver 中不起作用