자체 개발한 PHP 라이브러리 패키징 및 로컬 포함
1. 패키지 디렉터리 구조 생성
로컬에서 개발 중인 PHP 유틸리티 패키지를 my-utils라는 이름으로 구성합니다.
- 루트 디렉터리:
my-utils - 소스 코드 디렉터리:
my-utils/src
composer.json 초기화:
cd my-utils
composer init
생성된 기본 설정 예시:
{
"name": "dev/my-utils",
"description": "개발용 유틸리티 함수 모음",
"type": "library",
"license": "MIT",
"autoload": {
"psr-4": {
"Dev\\Utils\\": "src/"
}
},
"authors": [
{
"name": "Developer",
"email": "dev@example.com"
}
],
"minimum-stability": "dev",
"require": {
"php": "^8.0"
}
}
2. 핵심 기능 클래스 작성
응답 포맷 유틸리티 (ResponseFormatter)
src/ResponseFormatter.php 파일 생성:
<?php
namespace Dev\Utils;
class ResponseFormatter
{
public const CODE_OK = 200;
public const CODE_FAIL = 500;
private static array $messages = [
200 => '정상 처리되었습니다.',
500 => '서버 오류 발생'
];
public static function ok(array $data = [], ?string $msg = null): array
{
return self::build(self::CODE_OK, $msg ?? self::$messages[200], $data);
}
public static function fail(int $code = self::CODE_FAIL, ?string $msg = null, array $data = []): array
{
return self::build($code, $msg ?? self::$messages[$code] ?? '알 수 없는 오류', $data);
}
private static function build(int $code, string $message, array $payload): array
{
return [
'status' => $code,
'msg' => $message,
'result' => $payload
];
}
}
간단한 로그 기록기 (SimpleLogger)
src/SimpleLogger.php 파일 생성:
<?php
namespace Dev\Utils;
class SimpleLogger
{
private string $logDir;
private int $maxSize;
public function __construct(string $baseDir = './logs', int $sizeLimit = 2097152)
{
$this->logDir = rtrim($baseDir, '/') . '/' . date('Ym');
$this->maxSize = $sizeLimit;
}
private function ensureDirectory(): void
{
if (!is_dir($this->logDir)) {
mkdir($this->logDir, 0755, true);
}
}
private function shouldRotate(string $file): bool
{
return file_exists($file) && filesize($file) >= $this->maxSize;
}
private function rotateFile(string $file): void
{
$info = pathinfo($file);
$rotated = "{$info['dirname']}/{$info['filename']}_old_".time().".{$info['extension']}";
rename($file, $rotated);
}
public function log(string $channel, mixed $content, string $level = 'INFO'): bool
{
$this->ensureDirectory();
$filePath = "{$this->logDir}/{$channel}.log";
if ($this->shouldRotate($filePath)) {
$this->rotateFile($filePath);
}
$line = sprintf(
"[%s] %s: %s%s",
date('Y-m-d H:i:s'),
strtoupper($level),
is_string($content) ? $content : print_r($content, true),
PHP_EOL
);
return false !== file_put_contents($filePath, $line, FILE_APPEND | LOCK_EX);
}
}
3. 프로젝트에서 로컬 패키지 참조
기존 애플리케이션의composer.json에 로컬 저장소 등록:
"repositories": [
{
"type": "path",
"url": "../my-utils",
"options": {
"symlink": true
}
}
]
Windows 환경일 경우:
"url": "D:\\projects\\my-utils"
Linux/Mac 환경:
"url": "/home/user/projects/my-utils"
패키지 설치 명령:
composer require dev/my-utils
4. 실제 사용 예제
컨트롤러 또는 스크립트 내에서 활용:<?php
use Dev\Utils\ResponseFormatter;
use Dev\Utils\SimpleLogger;
// 응답 생성
$response = ResponseFormatter::ok([
'user_id' => 123,
'token' => 'abc123'
]);
// 로깅 처리
$logger = new SimpleLogger();
$logger->log('auth', 'User login attempt', 'DEBUG');
echo json_encode($response, JSON_UNESCAPED_UNICODE);