PHP開発にLaravelを使用する場合、フレームワークでは、デフォルトでデータベース操作にEloquent ORMとPDOを使用します。ただし、一部のシナリオでは、互換性またはパフォーマンスの理由で、開発者はMySQLI拡張機能によって提供された関数を使用してデータベースと対話することができます。 mysqli_stmt :: attr_getは、ステートメントプロパティの取得に使用されるmysqli_stmtクラスの方法です。
Laravelプロジェクトでより便利にmysqli_stmt :: attr_getを使用するために、それをカプセル化してデータベース接続とステートメント処理ロジックを均一に管理できます。以下は、特定のパッケージングスキームと実装手順です。
まず、 MySqliserviceなどのネイティブMySQLI操作をカプセル化するためのLaravelプロジェクトでサービスクラスを作成できます。
アプリ/サービスディレクトリでファイルmysqliservice.phpを作成します。
<?php
namespace App\Services;
class MysqliService
{
protected $mysqli;
public function __construct()
{
$this->connect();
}
protected function connect()
{
$this->mysqli = new \mysqli(
env('DB_HOST', 'localhost'),
env('DB_USERNAME', 'root'),
env('DB_PASSWORD', ''),
env('DB_DATABASE', 'forge'),
env('DB_PORT', 3306)
);
if ($this->mysqli->connect_error) {
throw new \Exception('Connect Error (' . $this->mysqli->connect_errno . ') ' . $this->mysqli->connect_error);
}
}
public function prepare($query)
{
$stmt = $this->mysqli->prepare($query);
if (!$stmt) {
throw new \Exception('Prepare failed: ' . $this->mysqli->error);
}
return $stmt;
}
public function getStatementAttribute($stmt, int $attr)
{
if (!($stmt instanceof \mysqli_stmt)) {
throw new \InvalidArgumentException('Invalid statement object provided.');
}
return $stmt->attr_get($attr);
}
public function close()
{
if ($this->mysqli) {
$this->mysqli->close();
}
}
}
コントローラーまたはその他のクラスでMySqliserviceを使用するために、 AppServiceProviderでサービスバインディングを実行できます。
アプリ/プロバイダー/appserviceprovider.phpの編集:
use App\Services\MysqliService;
public function register()
{
$this->app->singleton(MysqliService::class, function ($app) {
return new MysqliService();
});
}
これで、 mysqliserviceをコントローラーで直接使用し、 getStatementAttributeメソッドを呼び出してステートメント属性を取得できます。
サンプルコードは次のとおりです。
use App\Services\MysqliService;
class DatabaseController extends Controller
{
protected $mysqliService;
public function __construct(MysqliService $mysqliService)
{
$this->mysqliService = $mysqliService;
}
public function showAttribute()
{
$stmt = $this->mysqliService->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$email = "test@m66.net";
$stmt->execute();
// 取得したいとします MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH 財産
$attrValue = $this->mysqliService->getStatementAttribute($stmt, MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH);
$stmt->close();
$this->mysqliService->close();
return response()->json(['attribute_value' => $attrValue]);
}
}
ATTR_GETは、 MySQLI_STMTの比較的まれに使用されない方法であり、すべてのPHP環境がデフォルトでこの拡張法を有効にするわけではありません。展開前にその可用性を確認する必要があります。
LaravelでネイティブMySQLI操作を使用する場合は、サービスレイヤーとしてカプセル化し、システムの堅牢性を確保するためにロギングと例外処理を検討することをお勧めします。
MySqliはいくつかのシナリオで低レベルの制御機能を備えていますが、Laravelの雄弁でクエリビルダーは、ほとんどの場合、毎日の開発に適した高レベルの抽象化を提供します。
上記のカプセル化方法を使用して、Laravelでmysqli_stmt :: attr_getをエレガントに呼び出して、データベース接続とステートメント属性の集中管理を実現し、コードをより明確かつ保守可能にすることができます。