We can using Php magic method __callStatic in Laravel

Sử dụng phương thức `__callStatic()` . phương thức tĩnh (static method) là `__callStatic`. Phương thức này được gọi khi một phương thức tĩnh không tồn tại được gọi từ bên ngoài lớp.

Cụ thể, __callStatic được sử dụng để chuyển hướng cuộc gọi của các phương thức tĩnh không tồn tại đến một số phương thức đã được xác định trước (info, error, debug), bạn có thể cài đặt nhiều phương thức trong mảng in_array này nếu bạn muốn

VD:

class logger{
	public static function __callStatic($method,$arguments){
		if(in_array($method,['info','error','debug'])){
			$logMessage = strtoupper($method).':'.$arguments[0];
			echo $logMessage;
		}
		else{
			throw new \BadMethodCallException("Method $method does not exist in Logger");
		}
	}
}
 Logger::info('This is an information message');
 Logger::error('This is an error message');
 Logger::debug('this is a debug message');

Trong đoạn code bên trên ta sử dụng class Logger bên ngoài lớp(class). Nó không có ghi ra một file và cũng không ghi vào dữ liệu database cho chúng ta. Nó chỉ có tác dụng giúp hiện thị một message ra màn hình , cho chúng ta biết ta đang thực hiện thao tác nào

Các bạn thấy mảng ` in_array($method,['info','error','debug'])` , bạn có thể thêm các method bạn muốn, VD: in_array($method,['info','error','debug','adduser']), tôi thêm một method `adduser` và tôi sử dụng như đoạn code sau:

Logger::adduser('add user successfuly');

Các bạn thấy nó linh hoạt không, Quá ok hé, giờ ta phát triển nâng cao hơn là tạo một file text chứa các message log

class Logger {
    public static function __callStatic($method, $arguments) {
        if (in_array($method, ['info', 'error', 'debug','adduser'])) {
            // Thay vì in ra, ở đây bạn có thể ghi vào file hoặc cơ sở dữ liệu
            $logMessage = strtoupper($method) . ': ' . $arguments[0];
            // Ví dụ ghi log vào file
            file_put_contents('log.txt', $logMessage . PHP_EOL, FILE_APPEND);
        } else {
            throw new \BadMethodCallException("Method $method does not exist in Logger");
        }
    }
}

// Sử dụng
Logger::info('This is an information message');
Logger::error('This is an error message');
Logger::debug('This is a debug message');
Logger::adduser('add user successfuly');

Okay nếu trong Laravel thì ta có thể tạo một service để chưa class Logger để dễ sử dụng hơn

Trước hết, hãy tạo một class Logger trong thư mục Services:

php artisan make:provider LoggerServiceProvider

Sau khi tạo provider, bạn có thể định nghĩa class Logger trong LoggerServiceProvider:

// app/Providers/LoggerServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class LoggerServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('logger', function () {
            return new \App\Services\Logger(); // Định nghĩa class Logger ở đây
        });
    }
}

Tiếp theo, hãy tạo class Logger trong thư mục app/Services:

// app/Services/Logger.php
namespace App\Services;
class Logger
{
    public static function __callStatic($method, $arguments)
    {
        if (in_array($method, ['info', 'error', 'debug', 'adduser'])) {
            // Kiểm tra xem có đủ tham số log không
            if (count($arguments) !== 1) {
                throw new \InvalidArgumentException("Invalid number of arguments provided for method $method");
            }
            // Thay vì in ra, ở đây bạn có thể ghi vào file hoặc cơ sở dữ liệu
            $logMessage = strtoupper($method) . ': ' . $arguments[0];
            // Ví dụ ghi log vào file
            file_put_contents('log.txt', $logMessage . PHP_EOL, FILE_APPEND);
        } else {
            throw new \BadMethodCallException("Method $method does not exist in Logger");
        }
    }
}

Cuối cùng, bạn cần phải đăng ký LoggerServiceProvider trong config/app.php của Laravel:

// config/app.php
'providers' => [
    // ...
    App\Providers\LoggerServiceProvider::class,
    // ...
],

Sau khi đã thực hiện các bước trên, bạn có thể sử dụng Logger trong controller hoặc bất kỳ nơi nào trong ứng dụng Laravel của bạn:

<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Services\Logger; // Giả sử Logger là một service bạn đã tạo
class UserController extends Controller
{
    public function index()
    {
        // Ghi log thông tin về việc lấy thông tin tất cả người dùng
        Logger::info('Retrieving all users from database');
        // Lấy thông tin tất cả người dùng
        $users = User::all();
        // Xử lý dữ liệu $users...
        return view('users.index', compact('users'));
    }
}

Và bạn cũng có thể sử dụng các method sau:

use App\Services\Logger;

Logger::info('This is an information message');
Logger::error('This is an error message');
Logger::debug('This is a debug message');
Logger::adduser('New user added');

Okay vậy là xong, các bạn có thể sử dụng thử nhé

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)