search
HomeBackend DevelopmentPHP Tutorial基于Zend的Config机制的应用分析_PHP

Zend的Config类在Zend_Config_Ini

代码
$config = new Zend_Config_Ini("/var/www/html/usvn/config/config.ini", "general");

date_default_timezone_set($config->timezone);

USVN_ConsoleUtils::setLocale($config->system->locale);

===

Config.ini文件内容

[general]

url.base = "/usvn"

translation.locale = "zh_CN"

timezone = "Asia/Shanghai"


具体分析
这里只使用了Zend_Config_Ini的构造函数,我们看到它的__construct中。

首先是判断是否有配置文件。其次是对option进行管理,这里的option可以设置的有allowModifications属性(配置文件中的属性是否可以修改),nestSeparator属性(配置文件中的key分隔符,默认为点)。

下面是调用了$iniArray = $this->_loadIniFile($filename);这个函数非常重要,就是解析了配置文件。跟进去,先是调用了_parseIniFile,为了不让大家凌乱,我们看下_parseIniFile返回出来的数据是什么样子的:
复制代码 代码如下:
Array
(
    [general] => Array
        (
            [url.base] => /usvn
            [translation.locale] => zh_CN
            [timezone] => Asia/Shanghai
            [system.locale] => aa_DJ.utf8
        )

)

最后解析出来的东西是一个二维数组。

parseIniFile实际上是调用了系统函数parse_ini_file来进行处理的。这里特别注意一下,在调用parse_ini_file前后它其实使用了set_error_handler和restore_error_handler,将异常处理的函数暴露出来。因为在解析配置文件的时候其实非常容易出现错误,而且这个错误的用户提示应该要非常友好,最好能提示用户在那里进行修改,所以Zend特意将错误处理函数暴露出来。如果你想设计一款很友好的系统的话,请在继承类中重写方法_loadFileErrorHandler。

继续从_loadIniFile看下去

由于我们的ini配置文件中使用[]表示了一个setion,因此_loadIniFile返回的二维数组返回的key就是general。但是其实如果我们在配置文件中使用[general:123]作为section,那么这个函数就会将123作为[;extends]的val返回。实际是这样的
复制代码 代码如下:
Array
(
    [general] => Array
        (
            [;extends] => 123
            [url.base] => /usvn
            [translation.locale] => zh_CN
        )

)

现在又回到了__construct,这时候iniArray已经获取到了,是个二维数组,下面如果你设置了获取section的话,就会将iniArray进行处理_arrayMergeRecursive,主要就是将key中的system.locale => aa_DJ.utf8变为array(system=> array( locale=>aa_DJ.utf8))。 这里就是用到了options中的nestSeparator属性,这个属性默认是点,就是translation.locale会被分隔成数组,比如你在前面传入的nestSeparator为冒号,那么你的配置文件就应该设置为translation:location = .. 这里就不继续追下去了,里面无非就是一些字符串操作。

最后分析回来的dataArray是这个样子的
复制代码 代码如下:
Array
(
    [url] => Array
        (
            [base] => /usvn
        )

    [translation] => Array
        (
            [locale] => zh_CN
        )

    [timezone] => Asia/Shanghai
    [system] => Array
        (
            [locale] => aa_DJ.utf8
        )
)

下面调用父类的构造函数__construct, Zend_Config_Ini的父类是Zend_Config。


class Zend_Config implements Countable, Iterator

Zend_Config实现了Countable接口(包含count()方法),Iterator接口(包含current,key,next,rewind,valid等方法)

Zend_Config的构造函数将上面分析的二维数组放到_data中了。


这里注重看两个函数

__set和__get

魔术方法__get保证了可以使用config->field获取配置值

魔术方法__set保证了是否可以修改配置文件,set中就使用到了_allowModifications,如果这个属性有设置,那么__setter就可以设置,否则会抛出Zend_Config is read only的异常,allowModifications也是options中设置的属性之一。


至此,看文章最前面的demo代码

date_default_timezone_set($config->timezone);

这里之所以能使用->timezone就是使用了__get而不是config中的属性。
Zend的Config机制分析结束。

Statement
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
Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.