Home Backend Development PHP7 Yaconf usage tutorial for PHP7

Yaconf usage tutorial for PHP7

May 01, 2020 am 10:53 AM
php

This project is actually not a new idea. This is a small tool I made in my first optimization project after coming to Weibo. It is called Weibo_Conf. But because Weibo_Conf is a Weibo extension, there are also Some other functions are specially customized for Weibo. Therefore, they are not suitable for direct open source.

With the release of PHP7, many new persistence types have been added, such as IS_IMMUTABLE_ARRAY, so I redeveloped Yaconf under PHP7 , open source for everyone to use.

Introduction

First of all, let’s talk about what this does.

I have seen many projects , using PHP files for configuration, there may be a dozen or even dozens of .php configuration files in a config directory, which contain various arrays, and even some dictionary files (such as Chinese/English Control) is also put into the configuration. This causes the parsing of the configuration file to consume a lot of performance (admittedly, using opcache can be better, but in fact there is still an execution process).

Except PHP There are also those using json and yaml. A common feature is that the readability of these configurations is relatively poor. In addition, they also require runtime analysis.

The config directory is often together with the code. First there is Security risks (there are often sensitive information in the configuration). Secondly, if the configuration and code belong to the same project, this will cause the modification of the configuration to go through the process of code online.

Some resource configuration files, such as mysql/memcache Configuration information, these contents should be transparent to development, and operation and maintenance can be directly responsible. However, if it is put into the code, if operation and maintenance wants to initiate some changes, development and cooperation must be modified to modify the configuration file and go online.

So, Yaconf is a tool created to solve these problems.

It uses a separate configuration directory (specified in yaconf.directory), not together with the code.

It handles all the configurations to be processed when PHP starts, and then these configurations will reside in memory and live and die with the life cycle of PHP. It avoids parsing the configuration file every time it is requested.

All The configuration contents are all immutable, which can reduce memory usage with the help of Fork's COW, and when accessing the configuration, there is almost no need for any memory copy, and there will be no unnecessary increase or decrease in the reference count

The most important thing is that after the configuration directory and code are separated, a configuration management background can be used to achieve unified management of the configuration.

It supports (for non-ZTS) reloading of configuration changes, that is to say, the configuration If there are changes (it is recommended to use mv instead of cp to change the configuration), it will reload and does not need to be restarted (the frequency of detection is controlled by yaconf.check_delay).

It supports a variety of configuration types, including strings , array, section, section inheritance, and you can also write PHP constants and environment variables directly in the configuration.

The most important thing is, it is very simple.

API

Yaconf only provides two methods,

mixed Yaconf::get(string $name, mixed $default = NULL)
Copy after login

This is to get a configuration, the name is the name of the configuration, generally speaking, if you have an ini file called foo.ini , then if $name uses foo, it will get all the contents in this file and return it in the form of an array. default is the default value returned when the configuration does not exist.

bool Yaconf::has(string $name)
Copy after login

This is to detect whether a configuration exists .

Yaconf configuration items

yaconf.directory
Copy after login

Configuration file directory, this configuration cannot be specified through ini_set because it must be determined when PHP is started.

yaconf.check_delay
Copy after login

How often (seconds) to detect file changes, if it is 0, it will not be detected, that is to say, if it is 0, file changes can only be reloaded by restarting PHP

Configured format

Yaconf uses ini files as configuration files. This is because I have always felt that ini is the most suitable for configuration files. It is in key-value format and is clear and readable.

Simple configuration writing It looks like this (all the following assumes that the name of the ini file is test):

foo="bar"
phpversion=PHP_VERSION
env=${HOME}
Copy after login

As shown above, we use quotation marks for general configurations. For those that are not quoted, we will try to use PHP constants. Explanation, that is to say, we can write PHP constants directly in the configuration.

In addition, you can also see that we can write environment variables directly in the configuration, such as the above env:

Yaconf::get("test.env"); //test是配置文件名字
//string(16) "/home/huixinchen"
Copy after login

As shown above, you can see that assuming that the value of foo can be accessed through the following code:

Yaconf::get("test.foo"); //test是配置文件名字
Copy after login

Yaconf also supports array type configuration, which is written as follows:

arr.0=1
arr.1=2
Copy after login

If it is For a continuous array, you can also write directly:

arr[]=1
arr[]=2
Copy after login

Then for the value of the array, you can get it through the following code:

Yaconf::get("test.arr");
Copy after login

This will get the arr array in the test configuration file. Of course You can also directly obtain a specific value in the array. For example, if you want to directly obtain the 0th element of the arr array in the test configuration file:

$arr = Yaconf::get("test.arr.0");
Copy after login

Yaconf also supports map type configuration, which is written as follows:

map.foo=bar
map.bar=foo
Copy after login

;You can use semicolons to write comments

map2.foo.name=yaconf
map2.foo.year=2015
Copy after login

The name value of the foo submap of map2 can be accessed in the following form:

Yaconf::get("test.map2.foo.name"); //test是配置文件名字
Copy after login

And, the configuration file can also be divided into Section, and section inheritance:

[parent]
parent="base"
children="NULL"
[children : parent]
children="children"
Copy after login

Please pay attention to the configuration section inheritance syntax children: (colon) parent, which means that the children section inherits all base configuration items. Then you define it in the children section The configuration with the same name as the parent section will overwrite the content defined in the parent.

The value of the children configuration in the childlren section can be accessed in the following form:

Yaconf::get("test.children.children"); //test是配置文件名字
Copy after login

样例

首先, 假设我们的所有的配置文件都放置在/tmp/yaconf中, 那么我们就需要在php.ini中增加如下配置:

yaconf.directory=/tmp/yaconf
Copy after login

这样yaconf在PHP启动的时候, 就会在这个目录下找所有的*.ini文件, 然后尝试处理他们. 这里要注意的是不支持多级目录, 也就是说, yaconf只会处理yaconf.directory内的*.ini文件, 不会处理子目录里面的(这主要是为了简单考虑, 因为有分节, 你就可以一个项目定义一个ini文件).

假设/tmp/yaconf下有俩个ini文件, 分别是:

foo.ini

name="yaconf"
year=2015
features[]="fast"
features.1="light"
features.plus="zero-copy"
features.constant=PHP_VERSION
bar.ini
Copy after login

[base]

parent="yaconf"
children="NULL"
[children:base]
children="set"
Copy after login

然后对于foo的内容:

php7 -r 'var_dump(Yaconf::get("foo"));'
/*
array(3) {
  ["name"]=>
  string(6) "yaconf"
  ["year"]=>
  string(4) "2015"
  ["features"]=>
  array(4) {
    [0]=>
    string(4) "fast"
    [1]=>
    string(5) "light"
    ["plus"]=>
    string(9) "zero-copy"
    ["constant"]=>
    string(9) "7.0.0-dev"
  }
}
*/
Copy after login

对于bar的内容:

php7 -r 'var_dump(Yaconf::get("bar"));'
/*
array(2) {
  ["base"]=>
  array(2) {
    ["parent"]=>
    string(6) "yaconf"
    ["children"]=>
    string(4) "NULL"
  }
  ["children"]=>
  array(2) {
    ["parent"]=>
    string(6) "yaconf"
    ["children"]=>
    string(3) "set"
  }
}
*/
Copy after login

当然你可以用 (.)链接语法精确访问任何一个特定的值.

最后

我的Ya系列扩展从此又多了一个新成员, 算上之前的Yaf(PHP框架), Yar(PHP RPC框架), Yac(PHP单机缓存), 大家就可以很容易搭建一套高性能的LAMP应用解决方案出来.

注: Yaconf要求PHP7才能用 

推荐教程:《PHP7

The above is the detailed content of Yaconf usage tutorial for PHP7. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles