如何使用Doctrine命令工具从数据库生成实体?

6
我已经成功地将Doctrine安装到了我的Codeigniter项目中。 现在我遇到了一个问题,即无法与我的数据库通信,以从中生成实体。
来自我的Codeigniter应用程序/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);
  }
}

从我的 `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;

从我的 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中。这样,我可以像这样从我的控制器访问Doctrine:

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

From the output of the above print_r i can see which database settings where assigned when i first created the EntityManager connection

[_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
        )

So here comes the problem. Having everything properly installed i did open the terminal and navigated to the root of my codeigniter project. From there i typed:

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

according to the help function this is the syntax

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

This is what I'm getting printed on my terminal:

**[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

I'm getting frustrated. Can someone help me?


你需要将数据库凭据传递给Doctrine。类似这样的代码:$em = EntityManager::create($anArrayOfDbParams, $config); - Jay Bhatt
谢谢,我已经在“application/libraries/Doctrine.php”(帖子的第一段代码)中设置了Doctrine EntityManager。 - Lothre1
2个回答

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

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


http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/cookbook/code-igniter-and-doctrine.html - Vikas Gautam
数据库凭据是正确的。我可以确保这一点,因为我从命令行中使用它们。 - Lothre1

0

在深入研究问题后,我发现MAMP PRO设置导致Doctrine和我的DBMS(mysql)之间的通信出现问题。

为了解决这个问题,我尝试了三种不同的方法(我正在运行Mac)

  1. 将套接字的快捷方式添加到tmp文件夹和var/mysql文件夹中,如下所示:

sudo mkdir /var/mysql sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

  1. 将mysql添加到环境变量中
Open Terminal
      Type in:
          touch ~/.bash_profile; open ~/.bash_profile
          "this will open a text editor with all the environment variables"
      Alternative
          vim ~/.bash_profile
      Add the following line
          /Applications/MAMP/Library/bin
      SAVE CHANGES

      Type in (into command line)
          source ~/.bash_profile
  1. 要从数据库生成实体,我们只需在终端中键入以下命令

cd到/root/文件夹

php vendor/bin/doctrine orm:generate-entities application/models/Entities

输出 => 处理实体 "Message" 实体类生成到 "/Applications/MAMP/htdocs/DoctrineTest/application/models/Entities"

application/models/Entities 是我想要生成的模型所在的位置。 就这些。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接