大佬留言PHP8.3以下版本 直接使用webman提供的webman/think-orm
更方便、健全(見文末的留言)。
PHP 環(huán)境換為 8.4 使用webman/think-orm
報(bào)了個(gè)錯(cuò);所以換topthink/think-orm
,根據(jù)文檔其支持PHP8.0+,但實(shí)際情況還是報(bào)相同的錯(cuò)(錯(cuò)誤的暴力修改 在最后)。
業(yè)務(wù)初始化
業(yè)務(wù)初始化文檔地址 先熟讀此文檔,再做后續(xù)設(shè)置。topthink/think-orm
的文檔說明,安裝后,只需要設(shè)置數(shù)據(jù)庫配置信息即可。
use think\facade\Db;
Db::setConfig([
//配置數(shù)據(jù),看官網(wǎng)
]);
<?php
//命名空間根據(jù)自己的實(shí)際情況來
namespace app\init;
use Webman\Bootstrap;
use Workerman\Worker;
use think\facade\Db;
// use support\Log;
//注意類名需要和文件名一致
class ThinkOrmInit implements Bootstrap
{
public static function start(?Worker $worker)
{
$databaseConfig = config('think_orm');//在config目錄下建的一個(gè)think_orm.php配置文件,文件名隨便,配置復(fù)制官網(wǎng)的
// Log::info('databaseConfig:'.json_encode($databaseConfig));
if ($databaseConfig) {
Db::setConfig($databaseConfig);
// Db::connect();//AI生成是有此,但官方文檔不需要,所以沒要
}
}
}
4.2 修改config目錄下的 bootstrap.php 配置:
<?php
return [
support\bootstrap\Session::class,
support\bootstrap\LaravelDb::class,
app\init\ThinkOrmInit::class,//是的就是增加這個(gè)
];
PHP的 php.ini
文件開啟 extension=pdo_mysql
。
4.3 定義數(shù)據(jù)模型、數(shù)據(jù)的寫入。注: 只測(cè)了模型數(shù)據(jù)寫入,Db::name('user')->save($data);
這樣的數(shù)據(jù)寫入沒測(cè)試試。
只在前面提到的環(huán)境下測(cè)試,其他環(huán)境下需要進(jìn)一步驗(yàn)證。
下面描述的異常可能是我配置信息沒設(shè)置對(duì),導(dǎo)致$name
是null觸發(fā)的,熟悉 think-orm
的朋友,指導(dǎo)一下謝謝。
異常內(nèi)容如下:
ErrorException: think\DbManager::connect(): Implicitly marking parameter $name as nullable is deprecated, the explicit nullable type must be used instead in E:\x\項(xiàng)目\vendor\topthink\think-orm\src\DbManager.php:221
我的修改:找到文件、行,然后直接修改
221行
//原
public function connect(string $name = null, bool $force = false)
//改后 string $name 前加個(gè) ? 號(hào)
public function connect(?string $name = null, bool $force = false)
234行也有同樣的錯(cuò):
//原
protected function instance(string $name = null, bool $force = false): ConnectionInterface
//改后
protected function instance(?string $name = null, bool $force = false): ConnectionInterface
感謝分享。
為了避免誤導(dǎo),這里說明下
整個(gè)分享解決問題的路線就錯(cuò)了。webman/think-orm本身沒有問題,但是你又自己實(shí)現(xiàn)了一遍webman/think-orm的邏輯,并且邏輯里沒有考慮心跳、分頁配置等邏輯。
最后PHP8.4剛發(fā)布不久,目前市面上很多composer組件并不支持PHP8.4,不建議現(xiàn)在就開始使用PHP8.4,會(huì)給自己找來很多麻煩,就比如這篇文章。