将 Doctrine DBAL 添加到自己的 php 项目中

Add Doctrine DBAL into own php project

尝试将 Doctrine DBAL 添加到我自己的项目中以使用它来访问我的数据库等。我没有作曲家,而且我从未使用过它。这就是我根据文档要做的事情:

use Doctrine\Common\ClassLoader;

class Connection

{
    var $connection;

//Constructor
public function __construct()
{
    require_once "doctrine/Common/ClassLoader.php";

    $classLoader = new ClassLoader('Doctrine', 'doctrine');
    $classLoader->register();
    $config = new Configuration();
    $connectionParams = array(
        'dbname' => 'mydb',
        'user' => 'root',
        'password' => "",
        'host' => 'localhost',
        'driver' => 'pdo_mysql',
    );


    $this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
}
}

这是从这里截取的: -http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html 和: - http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/introduction.html

我已将 Common 和 DBAL 文件夹添加到我的项目中

我的文件夹结构如下所示:

    • 学说
      • DBAL
      • 普通
    • php东西
    • index.php(其中connection.php)被执行

所以根据我对代码所做的更改,我得到 "Cannot find class XY" 或类似的结果。我永远无法按照教程执行它。

我做错了什么?

我只想拥有连接对象,在那里我可以开始做我的事情,比如使用查询构建器等...

我完全迷失在这里...

更新:按要求安装了 composer,现在有了这个代码:

use Doctrine\DBAL\Configuration;

class Connection
{
    var $connection;

    //Constructor
    public function __construct()
    {
        $config = new Configuration();
        $connectionParams = array(
            'url' => 'mysql://root:secret@localhost/mydb',
        );
        $this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
    }

这是我的第一个 link 中的第二个代码示例。告诉我“Class 'Doctrine\DBAL\Configuration' 未找到”。有趣的是,IntelliJ 可以完美地自动完成路径(在路径中完成 DBAL 时建议我配置)但 PHP 找不到它。如果我删除新配置 PHP 只是告诉我,它找不到 DriverManager...

虽然我通过 composer 正确安装了它,但至少 composer 告诉我它现在已正确安装(composer 将库保存在哪里?)

注意命名空间的使用:如果它的加载器的Doctrine命名空间是Doctrine\Common\ClassLoader,你必须将文件放在Doctrine\Common文件夹中("Doctrine"大写"D").

请参阅 Doctrine DBAL 文档 Introduction chapter 中显示的代码片段。

您现在需要要求作曲家自动加载文件。

require __DIR__.'/vendor/autoload.php';
use Doctrine\DBAL\Configuration;

class Connection
{
    var $connection;

    //Constructor
    public function __construct()
    {
        $config = new Configuration();
        $connectionParams = array(
            'url' => 'mysql://root:secret@localhost/mydb',
        );
        $this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
    }

请注意,根据您的目录结构,自动加载文件可能在其他地方,但通常这应该有效。