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

Lot*_*re1 6 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

来自我的`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;
Run Code Online (Sandbox Code Playgroud)

从我的 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);
Run Code Online (Sandbox Code Playgroud)

通过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
Run Code Online (Sandbox Code Playgroud)

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 */
Run Code Online (Sandbox Code Playgroud)

为了我自己的方便,我添加了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');
    }
}
Run Code Online (Sandbox Code Playgroud)

从上面的输出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
        )
Run Code Online (Sandbox Code Playgroud)

所以这就是问题所在.安装好所有东西后,我确实打开了终端并导航到我的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
Run Code Online (Sandbox Code Playgroud)

我很沮丧.有人能帮我吗?

Lot*_*re1 0

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

为了解决这个问题,我尝试了 3 种不同的方法(我正在运行 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 。短袜

  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
Run Code Online (Sandbox Code Playgroud)
  1. 要从数据库生成实体,我们只需在终端中输入以下命令

cd 到/root/文件夹

php 供应商/bin/doctrine orm:生成实体应用程序/模型/实体

输出=>处理实体“消息”生成到“/Applications/MAMP/htdocs/DoctrineTest/application/models/Entities”的实体类

application/models/Entities 是我希望生成的模型所在的位置。这一切