@@ -512,35 +512,64 @@ Polluting globals is a bad practice in very languages because you could clash wi
512512library and the user of your API would be none-the-wiser until they get an exception in
513513production. Let's think about an example: what if you wanted to have configuration array.
514514You could write global function like ` config() ` , but it could clash with another library
515- that tried to do the same thing. This is why it
516- would be much better to use singleton design pattern and simple set configuration.
515+ that tried to do the same thing.
517516
518517** Bad:**
519518``` php
520- function config() {
519+ function config()
520+ {
521521 return [
522- 'foo': 'bar',
522+ 'foo' => 'bar',
523523 ]
524524}
525525```
526526
527527** Good:**
528+
529+ Create configuration file
530+
528531``` php
529- class Configuration {
530- private static $instance;
531- private function __construct($configuration) {/* */}
532- public static function getInstance() {
533- if (self::$instance === null) {
534- self::$instance = new Configuration();
535- }
536- return self::$instance;
532+ // config.php
533+ return [
534+ 'foo' => 'bar',
535+ ];
536+ ```
537+
538+ Or a [ YAML] ( https://en.wikipedia.org/wiki/YAML ) configuration file
539+
540+ ``` php
541+ // config.yml
542+ configuration:
543+ foo: 'bar'
544+ ```
545+
546+ Or something else
547+
548+ ``` php
549+ class Configuration
550+ {
551+ private $configuration = [];
552+
553+ public function __construct(array $configuration)
554+ {
555+ $this->configuration = $configuration;
556+ }
557+
558+ public function get($key)
559+ {
560+ return isset($this->configuration[$key]) ? $this->configuration[$key] : null;
537561 }
538- public function get($key) {/* */}
539- public function getAll() {/* */}
540562}
563+ ```
564+
565+ Load configuration from file and create instance of ` Configuration ` class
541566
542- $singleton = Configuration::getInstance();
567+ ``` php
568+ $configuration = new Configuration($configuration);
543569```
570+
571+ And now you must use instance of ` Configuration ` in your application.
572+
544573** [ ⬆ back to top] ( #table-of-contents ) **
545574
546575### Encapsulate conditionals
0 commit comments