현재 위치: > 최신 기사 목록> Laravel에서 Attr_get을 캡슐화하는 방법

Laravel에서 Attr_get을 캡슐화하는 방법

M66 2025-05-22

PHP 개발에 Laravel을 사용하는 경우 프레임 워크는 기본적으로 데이터베이스 작업에 Eloquent ORM 및 PDO를 사용합니다. 그러나 일부 시나리오에서 호환성 또는 성능상의 이유로 개발자는 MySQLI 확장에서 제공하는 기능을 직접 사용하여 데이터베이스와 상호 작용할 수 있습니다. mysqli_stmt :: attr_get은 명령문 속성을 얻는 데 사용되는 mysqli_stmt 클래스의 메소드이며, 데이터베이스 연결 동작을 디버깅하거나 세분화 할 때 매우 유용합니다.

Laravel 프로젝트에서 mysqli_stmt :: attr_get을 보다 편리하게 사용하려면이를 캡슐화하고 데이터베이스 연결을 관리하고 논리를 균일하게 처리 할 수 ​​있습니다. 다음은 특정 포장 체계 및 구현 단계입니다.

1. 사용자 정의 데이터베이스 서비스 클래스를 만듭니다

먼저 Laravel 프로젝트에서 MySQliservice 와 같은 기본 MySQLI 작업을 캡슐화하기 위해 서비스 클래스를 만들 수 있습니다.

앱/서비스 디렉토리에서 파일 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();
        }
    }
}

2. 서비스 컨테이너 바인딩 등록

컨트롤러 또는 기타 클래스에서 mysqliservice를 사용하려면 AppServiceProvider 에서 서비스 바인딩을 수행 할 수 있습니다.

앱/제공 업체/appserviceprovider.php 편집 :

 use App\Services\MysqliService;

public function register()
{
    $this->app->singleton(MysqliService::class, function ($app) {
        return new MysqliService();
    });
}

3. 컨트롤러에 패키지를 사용하는 방법

이제 컨트롤러에서 직접 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]);
    }
}

4. 주목할만한 것들

  • Att_get은 MySQLI_STMT 의 비교적 드물게 사용되는 방법이며 모든 PHP 환경이 기본적 으로이 확장 방법을 가능하게하는 것은 아닙니다. 배치 전에 가용성을 확인해야합니다.

  • Laravel에서 기본 MySQLI 작업을 사용하는 경우 서비스 계층으로 캡슐화하고 시스템의 견고성을 보장하기 위해 로깅 및 예외 처리를 고려하는 것이 좋습니다.

  • MySQLI는 일부 시나리오에서 낮은 수준의 제어 기능을 가지고 있지만 Laravel의 웅변 및 쿼리 빌더는 대부분의 경우 매일 개발에 더 적합한 높은 수준의 추상화를 제공합니다.

위의 캡슐화 방법을 통해 Laravel의 MySQLI_STMT :: ATTR_GET을 우아하게 호출하여 데이터베이스 연결 및 명령문 속성의 중앙 집중식 관리를 달성하여 코드를 더 명확하고 유지 관리 할 수 ​​있습니다.