【问题标题】:Integrating Doctrine with CodeIgniter将 Doctrine 与 CodeIgniter 集成
【发布时间】:2013-06-15 09:09:22
【问题描述】:

我已经成功安装了最新版本的 CodeIgniter 并且基本的 MVC 模式可以正常工作。我注意到的问题是 CI 在查询时自然不允许使用准备好的语句。所以,我决定从GitHub 下载 Doctrine 1。我对 Doctrine 很陌生,需要一些帮助将它与 CI 集成,所以我遵循了这个tutorial

在我的一个控制器中,我有

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

但是,当我在浏览器中加载视图时,我收到了一个读取错误

消息:require_once(/Applications/MAMP/htdocs/CodeIgniter/application/libraries/Doctrine/Common/ClassLoader.php):无法打开流:没有这样的文件或目录

在进一步检查从 GitHub 下载的 Doctrine 后,那里的任何地方似乎都没有一个名为“common”的文件夹。我对 CI 非常陌生,尤其是 Doctrine。有没有人有一些建议可以帮助我完成这项工作?另外,是否可以在 Doctrine 中使用 MySQLi 驱动程序而不是 PDO 驱动程序?

【问题讨论】:

    标签: codeigniter doctrine-orm


    【解决方案1】:

    直接从 GitHub 下载 Doctrine ORM 不包含其他依赖项。这些由Composer 管理。如果您查看 composer.json 文件,您可以看到这些依赖项。如果你想手动安装它们,它们是:

    • 教义/普通
    • 教义/变形者
    • 教义/缓存
    • 教义/收藏
    • 教义/词法分析器
    • 教义/注释
    • 教义/dbal
    • symfony/控制台

    我相信这就是全部。您必须将这些文件合并到相应的目录中,因为它们遵循 PSR-0 standards 以自动加载类。

    或者,使用 Composer 安装 Doctrine 2 并使用以下 composer.json 文件,任何其他依赖项都将自动安装。然后integrate with CodeIgniter

    {
        "minimum-stability": "stable",
        "require": {
            "doctrine/orm": "2.3.*"
        }
    }
    

    编辑 CodeIgniter 应用程序的 index.php 文件,方法是在需要 CodeIgniter 核心之前添加一行以包含自动加载器文件。

    require_once BASEPATH.'../vendor/autoload.php';
    
    require_once BASEPATH.'core/CodeIgniter.php';
    

    另外,如果使用 Composer 安装,请使用此编辑后的引导程序版本作为 application/libraries/Doctrine.php 的内容,这对我有用

    <?php
    
    use Doctrine\Common\ClassLoader,
        Doctrine\ORM\Tools\Setup,
        Doctrine\ORM\EntityManager;
    
    class Doctrine
    {
        public $em;
    
        public function __construct()
        {
            // Load the database configuration from CodeIgniter
            require APPPATH . 'config/database.php';
    
            $connection_options = array(
                'driver'        => 'pdo_mysql',
                'user'          => $db['default']['username'],
                'password'      => $db['default']['password'],
                'host'          => $db['default']['hostname'],
                'dbname'        => $db['default']['database'],
                'charset'       => $db['default']['char_set'],
                'driverOptions' => array(
                    'charset'   => $db['default']['char_set'],
                ),
            );
    
            // With this configuration, your model files need to be in application/models/Entity
            // e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
            $models_namespace = 'Entity';
            $models_path = APPPATH . 'models';
            $proxies_dir = APPPATH . 'models/Proxies';
            $metadata_paths = array(APPPATH . 'models');
    
            // Set $dev_mode to TRUE to disable caching while you develop
            $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies_dir);
            $this->em = EntityManager::create($connection_options, $config);
    
            $loader = new ClassLoader($models_namespace, $models_path);
            $loader->register();
        }
    }
    

    注意:CodeIgniter 的第 3 版发布后,可以与 Composer 一起安装,但第 2 版不能。

    【讨论】:

    • 对不起,我在最初的回答中犯了一个错误。我在 master 分支中看到了 composer.json,但没有检查它是否在 2.1-stable 分支中。我现在已经更正了。
    • 我仍然不太确定如何使用 Composer。学说下载里有一个json文件,不过就是这样。
    【解决方案2】:

    对于那些正在寻找将 Doctrine 2 与 CodeIgniter 集成的教程的人,这个问题和其他答案已经过时(对于 CI 2)。 这是我为 CI 3 制作的新教程,我​​检查了它是否有效:

    How to install Doctrine 2 in CodeIgniter 3


    我在这里重复一遍。

    安装 Doctrine

    Doctrine 2 ORM’s documentation - Installation and Configuration

    可以使用Composer 安装Doctrine。 在您的 composer.json 文件中定义以下要求:

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

    然后从命令行调用 composer install。

    与 CodeIgniter 集成

    Doctrine 2 ORM’s documentation - Integrating with CodeIgniter

    以下是步骤: 将一个名为 Doctrine.php 的 php 文件添加到您的 system/application/libraries 文件夹中。这将成为 D2 实体管理器的包装器/引导程序。 将 Doctrine 文件夹(包含 Common、DBAL 和 ORM 的文件夹)放在 third_party 文件夹中。 如果你愿意,打开你的 config/autoload.php 文件并自动加载你的 Doctrine 库:$autoload[‘libraries’] = array(‘doctrine’);

    创建您的 Doctrine CodeIgniter 库

    现在,您的 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';
    
        // include Doctrine's ClassLoader class
        require_once APPPATH.'third_party/Doctrine/Common/ClassLoader.php';
    
        // load the Doctrine classes        
        $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;  
        $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
        $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);
      }
    }
    

    设置命令行工具

    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
    

    对于生产模式,您需要使用真正的缓存系统,例如 APC,去掉 EchoSqlLogger,并在 Doctrine.php 中关闭 autoGenerateProxyClasses

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
    • 我听从了建议
    • 复制粘贴内容
    • @Abdulla:Daenu 说“最好包含答案的基本部分”,但您说的是“复制和粘贴内容”。我怎么能满足呢? SO 说Copy and Paste contents is a bad practice 只是为了另一个用户的答案,但我复制并粘贴了我的答案!
    • 因此您可以将其标记为重复
    【解决方案3】:

    在 CI 中找到学说集成的链接 https://github.com/mitul69/codeigniter-doctrine-integration

    【讨论】:

      【解决方案4】:

      请注意,code igniter 2 的代码组织略有不同。在 code igniter 2 中,最好将 Doctrine 文件夹放在 application/third_party 文件夹中,而不是 application/libraries 文件夹中(否则它将不起作用!)。

      您可以阅读更多关于它的信息here

      【讨论】:

        【解决方案5】:

        当我尝试按照学说用户指南中的本教程进行操作时,我遇到了同样的问题 http://doctrine-orm.readthedocs.org/en/latest/cookbook/integrating-with-codeigniter.html

        当我尝试通过 composer 安装时出现此问题,所以我去了这个网站 http://www.doctrine-project.org/downloads/ 并手动下载 DoctrineORM-2.3.3-full.tar.gz 版本,错误消失了。

        【讨论】:

          【解决方案6】:

          原发帖人的问题似乎是自动加载的问题。在尝试使用 Composer 设置 CodeIgniter 和 Doctrine 时,我遇到了类似的问题。在 CodeIgniter 3 中,您可以启用 Composer 自动加载,这应该允许您正确加载所有 Doctrine 文件。您必须将 Composer 供应商目录指向 application/vendor 才能使其正常工作。您也可以在旧版本中执行此操作,但是您必须在 CodeIgniter 的 Doctrine 库文件中手动包含 Composer 自动加载文件。 如果您想了解更多信息:我写了一篇博客文章,准确描述了如何做到这一点。 http://blog.beheist.com/integrating-codeigniter-and-doctrine-2-orm-with-composer/

          【讨论】:

          • 您能在此处添加您博客文章的某些部分吗?
          【解决方案7】:

          你可以用这个

          通过作曲家: composer create-project rbz/codeigniter your-project

          通过 git : git clone https://github.com/dandisy/cihmvctwig.git

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-18
            • 2020-11-20
            • 1970-01-01
            • 1970-01-01
            • 2016-01-26
            相关资源
            最近更新 更多