Php configure with json

The best setting.json for PHP development with Visual Studio Code

These features will be implemented by installing these extensions:

Step 1.

The first thing we need to do is disable default PHP support. This can be accomplished with two configuration items in your .vscode/settings.json file. The snippets in this post are extracted from the full file.

 "php.validate.enable": false, "php.suggest.basic": false, > 

This will allow our extensions to be used to their fullest extent and prevent any functional collisions.

Step 2.

By default, the php-redis extension is not included in the default configuration. So that means you will not have auto-complete for the Redis class. Now, let’s configure optimal Intelephense settings. Quick tip, when you’re editing a setting.json file in vscode, you can see the default value for the configuration item by typing the colon character, : and then clicking the tooltip.

"intelephense.stubs": [ "apache", "redis", "bcmath", "bz2", "calendar", "com_dotnet", "Core", "ctype", "curl", "date", "dba", "dom", "enchant", "exif", "fileinfo", "filter", "fpm", "ftp", "gd", "hash", "iconv", "imap", "interbase", "intl", "json", "ldap", "libxml", "mbstring", "mcrypt", "meta", "mssql", "mysqli", "oci8", "odbc", "openssl", "pcntl", "pcre", "PDO", "pdo_ibm", "pdo_mysql", "pdo_pgsql", "pdo_sqlite", "pgsql", "Phar", "posix", "pspell", "readline", "recode", "Reflection", "regex", "session", "shmop", "SimpleXML", "snmp", "soap", "sockets", "sodium", "SPL", "sqlite3", "standard", "superglobals", "sybase", "sysvmsg", "sysvsem", "sysvshm", "tidy", "tokenizer", "wddx", "xml", "xmlreader", "xmlrpc", "xmlwriter", "Zend OPcache", "zip", "zlib" ], "intelephense.telemetry.enabled": false, "intelephense.format.enable": true, "intelephense.completion.triggerParameterHints": true, "intelephense.completion.insertUseDeclaration": true, "intelephense.completion.fullyQualifyGlobalConstantsAndFunctions": true, "intelephense.trace.server": "messages", "intelephense.files.exclude": [ "**/.git/**", "**/.svn/**", "**/.hg/**", "**/CVS/**", "**/.DS_Store/**", "**/node_modules/**", "**/bower_components/**", "**/storage", "**/storage/**", "**/tests/**", "**/resources/views/**", "**/database/migrations/**", "**/storage/framework/views/**", "_ide_helper.php", "_ide_helper_models" ] 

Step 3 PHP Code Sniffer settings

"phpcs.executablePath": "vendor/bin/phpcs", "phpcs.enable": true, "phpcs.autoConfigSearch": true, "phpcs.standard": "./phpcs.xml", "phpcs.showWarnings": true, "phpcs.showSources": true, "phpcs.ignorePatterns": [ "**/.git/**", "**/.svn/**", "**/.hg/**", "**/CVS/**", "**/.DS_Store/**", "**/node_modules/**", "**/bower_components/**", "**/storage/**", "**/resources/views/**", "**/database/migrations/**", "**/tests/**", "**/storage/framework/views/**", "**/vendor", "_ide_helper.php", "_ide_helper_models" ] 

Step 4. PHPDoc Block settings

"php-docblocker.returnGap": true, "php-docblocker.qualifyClassNames": true, "php-docblocker.author":  "name": "Ryan McCullagh", "email": "ryan@amezmo.com" > 

Step 5. Optional settings.

These settings are more of a more personal flavor, but I’ve shared them here because I believe they are amazing.

"search.collapseResults": "alwaysCollapse", "search.exclude":  "**/node_modules": true, "**/bower_components": true, "**/.git": true, "**/storage": true, "**/tests": true, "_ide_helper.php": true, "_ide_helper_models.php": true, "package-lock.json": true >, "files.eol": "\n", "files.insertFinalNewline": true, "files.trimTrailingWhitespace": true, "files.associations":  "*.blade.php": "html", "*.php": "php", "*.vue": "vue", "*.php-cs": "php" >, "editor.fontSize": 14, "editor.letterSpacing": 0.5, "editor.lineHeight": 24, "editor.cursorBlinking": "smooth", "editor.fontLigatures": false, "editor.formatOnType": false, "editor.formatOnPaste": false, "editor.autoIndent": "advanced", "git.showPushSuccessNotification": true, "editor.gotoLocation.multipleDefinitions": "goto", "editor.snippetSuggestions": "bottom", "workbench.editor.enablePreview": false, "workbench.editor.enablePreviewFromQuickOpen": false, 

The last 2 are great because the editor will stay open when you’ve navigated to a file from a find all reference, or go to definition click.

Источник

Хранение и работа с настройками JSON + PHP ООП

Приветствую Вас хабравчане.
В течении нескольких лет разработки и поиска оптимальных решений для решения задач с использованием PHP перепробовал разные способы хранения и организации доступа к настройкам сайта. Одним из последних (и основных) способов хочу поделиться с Вами. Если похожие посты уже были — извиняюсь, не нашёл.

Требования и условия задачи

  • Удобство хранения и доступа
  • Высокая скорость работы
  • Глобальная область видимости
  • Относительно короткая запись
  • Хранение двух видов настроек: не изменяемых и переменных
  • PHP >= 5.3

Структура каталогов (+ файлов) сайта (для теста)

|-[classes]
| |-config.php
|-config.json
|-index.php

«Желаемый» способ доступа к настройкам

Исходный массив data:

$data = array( 'paramName_1' => array('paramName_2' => array('paramName_N' => 'value') ) ); 

Доступ к настройкам config.json:

// Прямой доступ к массиву: $value = cfg()->data['paramName_1']['paramName_2']['paramName_N']; // Доступ "как к объекту" $value = cfg()->paramName_1->paramName_2->paramName_N(); // и $value = cfg()->paramName_1->paramName_2('paramName_N'); 

Доступ к «глобальным изменяемым» настройкам:

// получить значение: $value = cfg()->varParam; // Запись значения: cfg()->varParam = 'value'; // и cfg()->varParam('value')->varParam_2(1234)->varParam_N(TRUE); 

JSON. Основной файл настроек (примерно)

< "site_name" : "SiteName", "site_slogan" : "слоган моего сайта", "http" : "http://", "domen" : "mysite.ru", "local_domen" : "mysite.local", "site_templates_name" : "def", "icon_name" : "icon.ico", "style_title_separator" : ":", "style_compress" : true, "www_compress" : true, "index_separator" : ">", "robots" : ["User-agent: *", "Allow: /", "Disallow: /search"], "date" : < "GMT" : "D, d M Y H:i:s" >, "db" : < "type" : "mysqli", "config":< "local" : < "dbName1" : >, "global": < "dbName1" : > > >, "session" : < "name" : "sid", "prefix" : "rgbetnm7_", "cookie_token_name" : "token", "life_time": 0, "db_life_time": 60, "token_key" : "nvgo275o2572067n20937hrstyrty3no49", "sess_token_name" : "x2kc85mv39cm29375nv69834noifjirhg" >> 

Содержимое INDEX.PHP

spl_autoload_extensions('.php'); spl_autoload_register(); define('DIRSEP', DIRECTORY_SEPARATOR); define('DIR', __DIR__); function cfg() < RETURN classes\Config::obj(); >/* остальной код */ 

Содержимое classes\CONFIG.PHP

class Config< //------------------------------ GLOBAL APP CONFIG ------------------------------// public $status = 200; // Default "200 OK"; Type (int) public $page_type = NULL; // глобальный параметр public $mode = NULL; // глобальный параметр //------------------------------ OBJECT & CONFIG.JSON ------------------------------// private $_data; // хранит в виде массива config.json private static $once = NULL; // хранит объект класса Config private static $file = 'config.json'; // имя файла private $get_arr = NULL; // индексный массив с именами ключей static function obj()< if(is_null(self::$once)): self::$once = new self(); $file = DIR . DIRSEP .self::$file; $json = is_file($file) ? file_get_contents($file) : NULL; self::$once->_data = json_decode($json, TRUE); endif; RETURN self::$once; > public function __get($name) < if($name === 'data') RETURN $this->_data; $this->get_arr[] = $name; RETURN self::obj(); > public function __call($name, $arg) < if(count($arg) >1) RETURN NULL; if( property_exists($this, $name) )< if(count($arg) !== 1) RETURN NULL; $this->$name = $arg[0]; RETURN self::obj(); >else< $this->get_arr[] = $name; $result = $this->_data; foreach ($this->get_arr as $name): if( !is_array($result) ) RETURN NULL; $result = $result[$name]; endforeach; $this->get_arr = NULL; RETURN isset($arg[0]) && is_array($result) ? $result[$arg[0]] : $result; > > public function __destruct() < $this->_data = NULL; > > 

ТЕСТИРУЕМ

Ниже приведённый способ доступа будет работать глобально, в любой части года.

// получаем префикс для локальной базы $dbPrefix = cfg()->db->config->local->dbName1->prefix(); // или $db_name = "dbName1"; $dbPrefix = cfg()->db->config->local->$db_name->prefix(); // или $dbPrefix = cfg()->db->config->local->$db_name('prefix'); // или $dbPrefix = cfg()->data['db']['config']['local'][$db_name]['prefix']; // Плохой способ: необходимо указывать имя массива + избыток скобок и кавычек // получаем robots с индексом 2 $robots_item = cfg()->robots(2); // вернёт значение "Disallow: /search" // получаем значение глобальной переменной $status = cfg()->status; // устанавливаем значения сразу нескольких глобальных переменных cfg()->status(404)->mode('www')->page_type('main'); 

Вывод

В результате получается достаточно компактный, понятный и читаемый код.

Источник

PHP config

PHP config tutorial shows how to create configuration files in PHP. It uses the hassankhan/config package.

$ php -v php -v PHP 8.1.2 (cli) (built: Aug 8 2022 07:28:23) (NTS) .

The hassankhan/config is a lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files. If we work with YAML files, we need to install symfony/yaml package.

Setting up PHP config

First, we install the necessary packages.

$ composer req hassankhan/config symfony/yaml

We install two packages with composer.

This is composer.json file. We also enable autoloading.

PHP config JSON example

In the first example, we read the configuration data from a JSON file.

We have db.json in the config directory.

get('app.port') . "\n"; echo $conf->get('db.host') . "\n"; echo $conf->get('db.port') . "\n"; echo $conf->get('db.name') . "\n";

We load the configuration file either with Config::load or Config . The values are retrieved with the get method. The dot character is used to go through the hierarchy of attributes.

$ php read_json_cfg.php 3000 localhost 27017 ydb

PHP YAML example

In the second example, we read configuration data from a YAML file.

app: port: 3000 db: host: localhost port: 27017 name: ydb
get('app.port') . "\n"; echo $conf->get('db.host') . "\n"; echo $conf->get('db.port') . "\n"; echo $conf->get('db.name') . "\n";

The example reads configuration file from the db.yaml file.

$conf = new Config('config/db.yaml', new Yaml);

In the second parameter, we provide the configuration parser.

$ php read_yaml_cfg.php 3000 localhost 27017 ydb

Merging configuration files

The merge method groups configuration files.

app: port: 3000 db: host: localhost port: 27017 name: ydb

This is the first configuration file.

This is the second configuration file.

merge($conf2); echo $conf->get('db.port') . "\n"; echo $conf->get('db.name') . "\n"; echo $conf->get('version') . "\n";

In the example we merge the two configuration files. We can access attributes from both files with one object.

Code configuration with AbstractConfig

We can specify the configuration details in code by using AbstractConfig .

 'localhost', 'port' => 80, 'servers' => [ 'host1', 'host2', 'host3' ] ]; > >

The configuration is specified in the AbstractConfig’s getDefaults file.

get('host') . "\n"; echo $conf->get('port') . "\n"; echo $conf->get('servers')[0] . "\n";

The example reads the configuration from the code.

In this article we have shown how to read configuration files in PHP with hassankhan/config package.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Читайте также:  Определение размера экрана java
Оцените статью