Current Location: Home> Latest Articles> How to encapsulate attr_get using in Laravel

How to encapsulate attr_get using in Laravel

M66 2025-05-22

When using Laravel for PHP development, the framework uses Eloquent ORM and PDO for database operations by default. However, in some scenarios, for compatibility or performance reasons, developers may directly use functions provided by the mysqli extension to interact with the database. mysqli_stmt::attr_get is a method of the mysqli_stmt class that is used to obtain statement properties, which is very useful when debugging or granularly managing database connection behavior.

In order to more conveniently use mysqli_stmt::attr_get in Laravel projects, we can encapsulate it and manage database connections and statement processing logic uniformly. The following are the specific packaging scheme and implementation steps.

1. Create a custom database service class

First, we can create a service class in the Laravel project for encapsulating native mysqli operations, such as MysqliService .

Create the file MysqliService.php in the app/Services directory:

 <?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. Register service container binding

In order to use MysqliService in controllers or other classes, service binding can be performed in AppServiceProvider .

Edit app/Providers/AppServiceProvider.php :

 use App\Services\MysqliService;

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

3. Methods for using packaged in the controller

Now we can use MysqliService directly in the controller and call the getStatementAttribute method to get the statement attributes.

The sample code is as follows:

 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();

        // Suppose we want to obtain MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH property
        $attrValue = $this->mysqliService->getStatementAttribute($stmt, MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH);

        $stmt->close();
        $this->mysqliService->close();

        return response()->json(['attribute_value' => $attrValue]);
    }
}

4. Things to note

  • attr_get is a relatively rarely used method of mysqli_stmt , and not all PHP environments enable this extension method by default. Its availability should be confirmed before deployment.

  • If you use native mysqli operations in Laravel, it is recommended to encapsulate it as a service layer and consider logging and exception handling to ensure the robustness of the system.

  • While mysqli has lower-level control capabilities in some scenarios, Laravel's Eloquent and Query Builder provide higher-level abstractions that are more suitable for daily development in most cases.

Through the above encapsulation method, we can gracefully call mysqli_stmt::attr_get in Laravel to achieve centralized management of database connections and statement attributes, making the code clearer and more maintainable.