CascadiaPHP 2024

PHP マニュアル

著者:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
2024-06-25
編集: Peter Cowburn
PHP マニュアル翻訳プロジェクト
add a note

User Contributed Notes 1 note

up
-1
simulationlaboratory2024 at gmail dot com
1 day ago
A better way to implement singleton desygn pattern and resquest data from a json file to connect to a database mysql. this is from my development project.

<?php
namespace Simulab\Simulab\models\connections;

/**
* Desygn Pattern: Construction: Singleton method.
*/
class SimulabConnection
{

private static
$instance = null;
private static
$pdo = null;

private function
__construct()
{

}

/**
* This method get information like servername, database, user and password from a json file
* All The informations about the database connections.
*/
public static function getJsonData():object{

$filename = '../../config/json/sgbd_informations.json';

if (
file_exists($filename)) {

$data = file_get_contents($filename);
$infodb= json_decode($data);

return
$infodb;
}else{
return
null;
}

}

public static function
connect():?\PDO{

if (
is_null(self::$instance)) {
self::$instance = new self;

$infodb= self::getJsonData()!=null?self::getJsonData():null;

$server= $infodb->server;
$database= $infodb->database;
$user= $infodb->user;
$password= $infodb->password;

$options= [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
self::$pdo = new \PDO("mysql:host=$server;dbname=$database", $user, $password, $options);

}

return
self::$pdo;

}

}
To Top