📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)
ページの作成:「== 概要 == 例外処理は、プログラムの実行中に予期せぬエラーが発生した場合、通常の処理フローを中断して特別な対応を行うための仕組みである。<br> PHPでは、エラーが発生した箇所から即座に処理を中断して、適切なエラー処理ルーチンにジャンプすることができる。<br> <br> <code>try</code>ブロックではエラーが発生する可能性のあるコードを配置し…」 |
|||
| 141行目: | 141行目: | ||
// エラー処理 | // エラー処理 | ||
} | } | ||
</syntaxhighlight> | |||
<br><br> | |||
== コンストラクタでの例外処理 == | |||
PHPでは、コンストラクタでも例外処理が可能である。<br> | |||
<br> | |||
ただし、以下に示すような注意がある。<br> | |||
* コンストラクタで例外が発生した場合、オブジェクトは正しく初期化されない。 | |||
* デストラクタは呼ばれない可能性がある。 | |||
* 例外が発生した場合、リソースの適切な開放が必要である。 | |||
<br> | |||
そのため、上記を考慮した安全な実装が必要となる。<br> | |||
* 段階的な初期化 | |||
*: コンストラクタは単純にして、初期化処理は別メソッドに委譲する。 | |||
*: 各初期化ステップを明確に分離する。 | |||
* 適切な例外処理 | |||
*: 具体的な例外クラスを使用する。 | |||
*: 例外の連鎖による詳細なエラー情報を保持する。 | |||
*: カスタム例外メッセージによる明確なエラー | |||
* リソース管理 | |||
*: クリーンアップ処理を実装する。 | |||
*: デストラクタでのリソース解放 | |||
<br> | |||
<syntaxhighlight lang="php"> | |||
class DatabaseConnection | |||
{ | |||
private ?PDO $pdo = null; | |||
private array $config = []; | |||
private string $iniPath; | |||
private string $section; | |||
/** | |||
* DatabaseConnectionの初期化 | |||
* | |||
* @param string $iniPath 設定ファイルのパス | |||
* @param string|null $section 使用するセクション名 | |||
* @throws RuntimeException 設定ファイルの読み込みに失敗した場合 | |||
* @throws InvalidArgumentException 無効なセクションが指定された場合 | |||
*/ | |||
public function __construct(string $iniPath = 'sample.ini', ?string $section = null) | |||
{ | |||
$this->iniPath = $iniPath; | |||
$this->section = $section ?? getenv('APP_ENV') ?: 'development'; | |||
// 初期化処理を別メソッドに委譲 | |||
$this->initialize(); | |||
} | |||
// 接続の初期化処理 | |||
private function initialize(): void | |||
{ | |||
try { | |||
$this->loadConfiguration(); | |||
$this->establishConnection(); | |||
} | |||
catch (Exception $e) { | |||
// 初期化中に発生した例外を適切にラップして再スロー | |||
$this->cleanup(); | |||
throw new RuntimeException("データベース接続の初期化に失敗: " . $e->getMessage(), 0, $e); | |||
} | |||
} | |||
// 設定ファイルの読み込み | |||
private function loadConfiguration(): void | |||
{ | |||
if (!file_exists($this->iniPath)) throw new RuntimeException("設定ファイル {$this->iniPath} が存在しない"); | |||
$this->config = parse_ini_file($this->iniPath, true); | |||
if ($this->config === false) throw new RuntimeException('設定ファイルの読み込みに失敗'); | |||
if (!isset($this->config[$this->section])) { | |||
throw new InvalidArgumentException("指定されたセクション '{$this->section}' が存在しない"); | |||
} | |||
} | |||
// データベース接続の確立 | |||
private function establishConnection(): void | |||
{ | |||
$sectionConfig = $this->config[$this->section]; | |||
// 必須パラメータのチェック | |||
$requiredParams = ['host', 'dbname']; | |||
foreach ($requiredParams as $param) { | |||
if (empty($sectionConfig[$param])) { | |||
throw new InvalidArgumentException("必須パラメータ {$param} が設定されていない"); | |||
} | |||
} | |||
$host = $sectionConfig['host']; | |||
$dbname = $sectionConfig['dbname']; | |||
$username = $sectionConfig['username'] ?? 'root'; | |||
$password = $sectionConfig['password'] ?? ''; | |||
$charset = $sectionConfig['charset'] ?? 'utf8mb4'; | |||
$dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}"; | |||
$options = [ | |||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, | |||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, | |||
PDO::ATTR_EMULATE_PREPARES => false, | |||
]; | |||
try { | |||
$this->pdo = new PDO($dsn, $username, $password, $options); | |||
} | |||
catch (PDOException $e) { | |||
throw new RuntimeException("データベース接続に失敗: " . $e->getMessage(), 0, $e); | |||
} | |||
} | |||
// リソースのクリーンアップ | |||
private function cleanup(): void | |||
{ | |||
$this->pdo = null; | |||
$this->config = []; | |||
} | |||
// デストラクタ | |||
public function __destruct() | |||
{ | |||
$this->cleanup(); | |||
} | |||
// PDO接続を取得 | |||
public function getConnection(): PDO | |||
{ | |||
if ($this->pdo === null) throw new RuntimeException('データベース接続が初期化されていない'); | |||
return $this->pdo; | |||
} | |||
// 接続テスト | |||
public function testConnection(): bool | |||
{ | |||
try { | |||
$this->getConnection()->query('SELECT 1'); | |||
return true; | |||
} | |||
catch (Exception $e) { | |||
return false; | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
<syntaxhighlight lang="php"> | |||
// 使用例 | |||
try { | |||
// データベース接続のインスタンスを作成 | |||
$db = new DatabaseConnection(); | |||
// 接続テスト | |||
if ($db->testConnection()) { | |||
echo "データベースへの接続に成功"; | |||
// データベース操作の例 | |||
$pdo = $db->getConnection(); | |||
$stmt = $pdo->query('SELECT version()'); | |||
$version = $stmt->fetchColumn(); | |||
echo "MySQL バージョン: " . $version; | |||
} | |||
} | |||
catch (Exception $e) { | |||
echo "エラー: " . $e->getMessage(); | |||
error_log($e->getMessage()); | |||
} | |||
?> | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<br><br> | <br><br> | ||