PHP 连接 Oracle
起因#
由于项目的数据库需要用客户购买的 Oracle 数据库,所以需要 php 安装 oci 扩展。
运行环境#
php
: 7.2
系统
: windows10
oracle
: 11gR2
安装相关环境#
由于 php 的 oci8 扩展还是需要使用到 oracle 的一些包,所以先下载这一些。
下载完成后解压缩这个压缩包,并且将这个包的路径添加到 PATH 中。
下载 php 的 oci8 扩展#
windows 可以直接到这个网址上下载相应的 dll,pecl oci8
如果是安装了 pecl 的话,可以直接运行 pecl install oci8
下载完成后放到 php 的 ext 目录下,并且编辑 php.ini
文件,添加 extension=php_oci8.dll
这样就完成了 php 与 oracle 的配置了。
在 Laravel 中使用#
Laravel 默认支持的数据库不包含 oracle,可以使用 yajra/laravel-oci8 这一个包来让 Laravel 支持 oracle
composer require yajra/laravel-oci8
由于这个包已经支持 Laravel 的自动加载,也就不需要自己手动去注册了
"extra": {
"branch-alias": {
"dev-master": "5.6-dev"
},
"laravel": {
"providers": [
"Yajra\\Oci8\\Oci8ServiceProvider"
]
}
},
这样就可以使用 php 连接到 oracle 了。
一个坑#
我们在使用 migration 来管理表格的时候,一般情况下会对每一个表都要有注释(为了别人能看得懂。。。)。然而这个包有一个 bug,就是对于表格的注释缺少了前缀。
表格的注释是
成员变量
而不是方法
噢。
/**
* Run the comment on table statement.
* Comment set by $table->comment = 'comment';.
*
* @param \Yajra\Oci8\Schema\OracleBlueprint $blueprint
*/
private function commentTable(OracleBlueprint $blueprint)
{
$table = $this->wrapValue($blueprint->getTable());
if ($blueprint->comment != null) {
$this->connection->statement("comment on table {$table} is '{$blueprint->comment}'");
}
}
这一段代码在 /vendor/yajar/laravel-oci8/src/Oci8/Schema/Comment.php
中第 40 行。
这里少了对表前缀的引用,导致我们在 migrate 的时候生成的 sql 是缺少了表前缀的,所以在这里添加一个表前缀上去解决这个问题
/**
* Run the comment on table statement.
* Comment set by $table->comment = 'comment';.
*
* @param \Yajra\Oci8\Schema\OracleBlueprint $blueprint
*/
private function commentTable(OracleBlueprint $blueprint)
{
$table = $this->wrapValue($blueprint->getTable());
if ($blueprint->comment != null) {
$this->connection->statement("comment on table {$this->connection->getTablePrefix()}{$table} is '{$blueprint->comment}'");
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: