Answer the question
In order to leave comments, you need to log in
What can be improved/fixed in the class (Singleton)?
I finally got down to fundamental things in order to tighten up the theoretical base.
I am currently reading a book by Matt Zandstra - PHP: Objects, Patterns and Programming Techniques.
I got to the chapter with patterns and I'm trying it in practice I
wrote a class to get the configuration using Singleton,
please tell me what jambs are there? What could be improved/fixed
<?php
namespace App\Core;
use Symfony\Component\Dotenv\Dotenv;
/**
* Class Config
* @package App\Core
*/
class Config {
/**
* @var static
*/
private static $instance;
/**
* @var array
*/
private $params = [];
/**
* Config constructor.
*/
private function __construct() {
$dotenv = new Dotenv();
// здесь немного смущает путь к конфигурационному файлу
$dotenv->load( __DIR__ . '/../../.env' );
$this->params = $_ENV;
}
/**
* @return static
*/
public static function getInstance(): self {
// в этом методе можно использовать и static и self Есть ли какая то разница
if ( empty( self::$instance ) ) {
return new Config();
}
return self::$instance;
}
/**
* @return array
*/
public function getParams(): array {
return $this->params;
}
/**
* @param string $key
*
* @return string
*/
public function getParam( string $key ): string {
return $this->params[ $key ];
}
}
Answer the question
In order to leave comments, you need to log in
public static function getInstance(): self {
if ( empty( self::$instance ) ) {
self::$instance = new Config();
}
return self::$instance;
}
You can also ask the class https://refactoring.guru/en/design-patterns/singleton
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question