【问题标题】:How to install Doctrine in CodeIgniter 3如何在 CodeIgniter 3 中安装 Doctrine
【发布时间】:2016-01-17 12:50:51
【问题描述】:

official guide 不完整,others 用于 CI2。

所以我给你一个我自己检查过的教程。

我知道鼓励用户to answer their own questions

【问题讨论】:

    标签: codeigniter doctrine-orm codeigniter-3


    【解决方案1】:

    安装 Doctrine

    (以下指令修改自:Doctrine 2 ORM’s documentation - Installation and Configuration

    可以用Composer安装Doctrine:

    1. 从您的命令行(例如 Windows:开始 > cmd),切换到应安装文件的文件夹(例如 htdocs/my_project)。

    2. 使用 Composer 安装文件:

      一个。运行C:\>composer install doctrine/orm

      或:

      b.在您的 composer.json 文件中定义以下要求:

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

      然后从命令行调用composer install

    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’s documentation - Integrating with CodeIgniter

    1. 创建您的 Doctrine 库:在您的文件夹 system/application/libraries 中,创建一个名为 Doctrine.php 的文件并将以下代码复制/粘贴到该文件中。这将成为 Doctrine2 实体管理器的包装器/引导程序。

      您的 Doctrine.php 库文件应如下所示(您可以根据需要对其进行自定义):

      <?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. 加载理论库:或者通过将其添加到 application/config/autoload.php 文件中的数组来自动加载您的 Doctrine 库:

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

    或像任何其他库一样手动将其加载到您的控制器中,方法是:

    $this-&gt;load-&gt;library('doctrine');

    如果你在applications/third_party 中安装了Doctrine.php,你会使用:

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

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

    接下来是什么中提供了一个示例控制器。


    设置命令行工具

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

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

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

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

     <?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
    

    如果您收到此错误: 致命错误:调用未定义函数 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,请从控制器中调用它,例如:

    应用程序/控制器/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。
    【解决方案2】:

    对于 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);
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2019-08-14
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多