如何在CodeIgniter 3中安装Doctrine

10
2个回答

8

安装Doctrine

(以下说明修改自:Doctrine 2 ORM的文档 - 安装和配置

可以使用Composer安装Doctrine:

  1. From your command line (e.g. Windows: Start > cmd), change to the folder where the files should be installed (e.g. htdocs/my_project).

  2. Use Composer to install the files:

    a. run C:\>composer install doctrine/orm

    or:

    b. Define the following requirement in your composer.json file:

    {
    "require": {
        "doctrine/orm": "*"
      }
    }
    

    and then call composer install from your command line.

Composer会安装一个名为vendor的文件夹,其中包含许多子文件夹和数百个php文件。将此vendor文件夹移动到您的CodeIgniter应用程序树中。为了简单起见,您可以将其放在这里:

/application
    /config
    /controllers
    /libraries
       Doctrine.php <-- the doctrine bootstrap/wrapper file
    /third_party
/vendor  <-- the folder installed by Composer. don't touch the files or folders below it -- install all together as one happy family.
    /bin
    /composer
    /doctrine
    /symfony
    autoload.php  <-- Doctrine.php opens this to load its files

然后在您的库文件Doctrine.php中(见下文),您只需要:

require_once FCPATH . 'vendor/autoload.php';  // FCPATH is a CI constant specifies the path to the front controller.

您还可以将vendor文件夹中包含的所有文件和文件夹安装到其他位置,例如third_party文件夹,并相应地调整您的Doctrine.php文件。


与CodeIgniter集成

(以下说明修改自:Doctrine 2 ORM文档 - 与CodeIgniter集成

  1. Create your Doctrine library: In your folder system/application/libraries, create a file named Doctrine.php and copy/paste the following code into the file. This is going to be your wrapper/bootstrap for the Doctrine2 entity manager.

    Your Doctrine.php library file should look like this (you may customize it to your needs):

    <?php
    /**
    * Doctrine 2.4 bootstrap
    *
    */
    
    use Doctrine\Common\ClassLoader,
       Doctrine\ORM\Configuration,
       Doctrine\ORM\EntityManager,
       Doctrine\Common\Cache\ArrayCache,
       Doctrine\DBAL\Logging\EchoSQLLogger;
    
    
    class Doctrine {
    
       public $em = null;
    
       public function __construct()
       {
         // load database configuration from CodeIgniter
         require_once APPPATH.'config/database.php';
    
        // load Doctrine
        require_once FCPATH . 'vendor/autoload.php';
    
        // or, if you installed another way, you could:
        // require_once APPPATH.'third_party/Doctrine/Common/ClassLoader.php';
    
        // load the Doctrine classes        
        $doctrineClassLoader = new ClassLoader('Doctrine',  APPPATH.'libraries');
        // or, if installed in third_party: 
        // $doctrineClassLoader = new ClassLoader('Doctrine',  APPPATH.'third_party');
        $doctrineClassLoader->register();
        // load the entities
        $entityClassLoader = new ClassLoader('Entities', APPPATH.'models');
        $entityClassLoader->register();
        // load the proxy entities
        $proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies');
        $proxiesClassLoader->register();
        // load Symfony2 classes
        // this is necessary for YAML mapping files and for Command Line Interface (cli-doctrine.php)
        $symfonyClassLoader = new ClassLoader('Symfony',  APPPATH.'third_party/Doctrine');
        $symfonyClassLoader->register();
    
        // Set up the configuration
        $config = new Configuration;
    
        // Set up caches
        if(ENVIRONMENT == 'development'):  // set environment in index.php
            // set up simple array caching for development mode
            $cache = new \Doctrine\Common\Cache\ArrayCache;
        else:
            // set up caching with APC for production mode
            $cache = new \Doctrine\Common\Cache\ApcCache;  
        endif;
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);
    
        // set up annotation driver
        $driver = new \Doctrine\ORM\Mapping\Driver\PHPDriver(APPPATH.'models/Mappings');
        $config->setMetadataDriverImpl($driver);
    
        // Proxy configuration
        $config->setProxyDir(APPPATH.'/models/Proxies');
        $config->setProxyNamespace('Proxies');
    
        // Set up logger (recommended to remove for production)
        $logger = new EchoSQLLogger;
        $config->setSQLLogger($logger);
    
        $config->setAutoGenerateProxyClasses( TRUE ); // only for development
    
        // 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, and store it for use in our CodeIgniter controllers
        $this->em = EntityManager::create($connectionOptions, $config);
      }
    }
    
  2. Load the doctrine library: either autoload your Doctrine library by adding it to the array in your application/config/autoload.php file:

    '$autoload[‘libraries’] = array(‘doctrine’);`

或者像加载其他库一样,在控制器中手动加载它,使用:

$this->load->library('doctrine');

如果你将Doctrine.php安装在applications/third_party中,你需要使用:

$autoload['libraries'] = array('third_party/doctrine');

或者

$this->load->library('third_party/doctrine');

下面提供了一个示例控制器,请参考接下来的步骤


设置命令行工具

Doctrine附带了许多命令行工具,在开发过程中非常有用。

检查Doctrine.php文件中是否存在这些行,以便加载Symfony类来使用命令行工具(以及YAML映射文件):

$symfonyClassLoader = new ClassLoader('Symfony', APPPATH.'third_party/Doctrine');
$symfonyClassLoader->register();

您需要将应用程序的EntityManager注册到控制台工具中,以便通过在应用程序目录中创建cli-doctrine.php文件并包含以下内容来使用任务:

 <?php

 /**
 * Doctrine CLI bootstrap for CodeIgniter
 *
 */

 define('APPPATH', dirname(__FILE__) . '/');
define('BASEPATH', APPPATH . '/../system/');
define('ENVIRONMENT', 'development');

 require APPPATH.'libraries/Doctrine.php';

$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);

 ?>

现在通过PHP命令行运行此脚本,您应该能够看到可用于您的命令列表。
php cli-doctrine.php

从数据库生成映射类:
php cli-doctrine.php orm:convert-mapping --from-database annotation models/Entities

如果你遇到这个错误: Fatal error: Call to undefined function Doctrine\Common\Cache\apc_fetch() 请安装PHP的APC扩展:
sudo apt-get install php-apc
sudo /etc/init.d/apache2 restart

生产模式下: Doctrine 建议在 Doctrine.php 中更改以下设置: - 使用真正的缓存系统,例如 APC - 禁用 EchoSqlLogger - 关闭 autoGenerateProxyClasses


下一步是什么

要在CI中使用Doctrine,请从控制器中调用它,例如:

application/controllers/my_controller.php:

function doctrine_orm()
{
    $this->load->library('Doctrine');
    $em = $this->doctrine->em;

    // do Doctrine stuff
    $productRepository = $em->getRepository('Product');
    $products = $productRepository->findAll();
    foreach ($products as $product):
        echo sprintf("-%s\n", $product->getName());
    endforeach;
}

然而,在进行任何Doctrine操作之前,您必须首先将数据库表映射到Doctrine "实体"。在此处了解如何操作: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/tutorials/getting-started.html


请按照以下步骤操作,以确保Doctrine 2.4和CodeIgniter 3.1.4正常工作。 - gvd

1
对于CI3 + HMVC + Doctrine 2.4。
<?php

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\Common\ClassLoader;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Event\Listeners\MysqlSessionInit;
use Doctrine\DBAL\Logging\EchoSQLLogger;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\Tools\SchemaTool;
use Gedmo\Sluggable\SluggableListener;
use Gedmo\Timestampable\TimestampableListener;
use Gedmo\Tree\TreeListener;

class Doctrine
{

    public $em = null;
    public $tool = null;

    public function __construct()
    {

        // Is the config file in the environment folder?
        if (!defined('ENVIRONMENT') OR !file_exists($file_path = APPPATH . 'config/' . ENVIRONMENT . '/database.php')) {
            $file_path = APPPATH . 'config/database.php';
        }
        // load database configuration from CodeIgniter
        require $file_path;


        // Set up class loading. You could use different autoloaders, provided by your favorite framework,
        // if you want to.
        require_once APPPATH . 'vendor/doctrine/common/lib/Doctrine/Common/ClassLoader.php';

        $doctrineClassLoader = new ClassLoader('Doctrine', APPPATH . 'libraries');
        $doctrineClassLoader->register();
        $entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/"));
        $entitiesClassLoader->register();
        $proxiesClassLoader = new ClassLoader('Proxies', APPPATH . 'proxies');
        $proxiesClassLoader->register();


        foreach (glob(APPPATH . 'modules/*', GLOB_ONLYDIR) as $m) {
            $module = str_replace(APPPATH . 'modules/', '', $m);
            $loader = new ClassLoader($module, APPPATH . 'modules');
            $loader->register();
        }


        $evm = new EventManager;
        // timestampable
        $evm->addEventSubscriber(new TimestampableListener);
        // sluggable
        $evm->addEventSubscriber(new SluggableListener);
        // tree
        $evm->addEventSubscriber(new TreeListener);


        // 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);

        $config->setQueryCacheImpl($cache);

        // Proxy configuration
        $config->setProxyDir(APPPATH . '/proxies'); //must be set to 777
        $config->setProxyNamespace('Proxies');

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


        if (ENVIRONMENT == "development") {
            $config->setAutoGenerateProxyClasses(true);
        } else {
            $config->setAutoGenerateProxyClasses(false);
        }


        // Database connection information
        $connectionOptions = array(
            'driver' => 'pdo_mysql',
            'user' => $db[$active_group]['username'],
            'password' => $db[$active_group]['password'],
            'host' => $db[$active_group]['hostname'],
            'dbname' => $db[$active_group]['database']
        );

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


        // Force UTF-8
        $this->em->getEventManager()->addEventSubscriber(new MysqlSessionInit('utf8', 'utf8_unicode_ci'));

        // Schema Tool
        $this->tool = new SchemaTool($this->em);

    }
}

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