尝试将 Doctrine DBAL 添加到我自己的项目中,以使用它来访问我的数据库等。我没有 Composer ,而且我从未使用过它。这就是我根据文档尝试做的事情:
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)
- 学说
所以发生的情况是,根据我对代码的更改,我要么得到“找不到类 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);
}
这是我的第一个链接中的第二个代码示例。告诉我“找不到类'Doctrine\DBAL\Configuration'”。有趣的是,IntelliJ 可以完美地自动完成路径(建议我在完成路径中的 DBAL 时配置),但 PHP 找不到它。如果我删除新的配置 PHP 只会告诉我,它找不到 DriverManager...
我通过composer正确安装了它,至少composer告诉我它现在安装正确了(composer在哪里保存库?)
最佳答案
您现在需要要求 Composer 自动加载文件。
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);
}
请注意,根据您的目录结构,自动加载文件可能位于其他位置,但通常这应该可以工作。
关于php - 将 Doctrine DBAL 添加到自己的 php 项目中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908754/