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

时间:2014-01-31 18:59:20

标签: php codeigniter doctrine-orm

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

来自我的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);
  }
}

来自我的`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);

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

{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 这样我可以从我的控制器访问学说:

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

我感到很沮丧。有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

在深入研究问题后,我发现MAMP PRO设置导致了学说与我的DBMS(mysql)之间的问题。

为了解决这个问题,我尝试了3种不同的东西(我正在运行mac)

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

    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添加到环境变量
    2. 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. 要从数据库生成实体,我们只需在终端
      2. 中键入以下命令即可
          

        cd到/ root / folder

             

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

        输出=&gt;处理实体“消息” 生成的实体类为“/ Applications / MAMP / htdocs / DoctrineTest / application / models / Entities”

        应用程序/模型/实体是我希望生成模型的位置。 那一切