How to Build PHP programs using different files _ PHP Tutorial

Source: Internet
Author: User
Tags configuration settings
Build PHP programs using different files. Different files build PHP programs in the following way: if you plan to allow others or companies to use your php application, make sure the program is configurable. At least, the way PHP programs are built with different files

Reference content is as follows:

If you plan to allow others or companies to use your php application, make sure it is configurable. At least, you must allow the user to set the database logon and password in a safe way, so that the materials are not disclosed to the public.

This article describes several technologies used to store configuration settings and edit these settings. In addition, this article provides guidance on which elements need to be configured and how to avoid excessive configuration or insufficient configuration.

Use the INI file for configuration

PHP has built-in support for configuration files. This is implemented through the initialization file (ini) mechanism like the php. INI file, which defines constants such as database connection timeout or session storage. If you want to, you can customize the configuration for the application in this php. ini file. For instructions, I add the following lines of code to the php. ini file.

Myapptempdir = foo

Then, I wrote a small PHP script to read this configuration item, as shown in listing 1.

Listing 1. ini1.php

  

Function get_template_directory ()

{

$ V = get_cmd_var ("myapptempdir ");

Return ($ v = null )? "Tempdir": $ v;

}

Echo (get_template_directory ()."");

?>

When you run this code in the command line, the following results are obtained:

% Php ini1.php

Foo

%

Great. But why cannot I use the standard INI function to obtain the value of the myapptempdir configuration item? I have studied and found that in most cases, custom configuration items cannot be obtained using these methods. However, the get_cfg_var function is accessible.

To make this method simpler, the access to the variable is encapsulated in the second function. the function uses the configuration key name and a default value as the parameter, as shown below.

Listing 2. ini2.php

Function get_ini_value ($ n, $ dv)

{

$ C = get_cfg_var ($ n );

Return ($ c = null )? $ Dv: $ c;

}

Function get_template_directory ()

{

Return get_ini_value ("myapptempdir", "tempdir ");

}

This is a good generalization of how to access the INI file. Therefore, if you want to use a different mechanism or store the INI file to another location, you don't have to worry about changing a large number of functions.

I do not recommend using the INI file for application configuration. There are two reasons. First, although it is easier to read INI files, it is almost impossible to write INI files safely. Therefore, this method is only applicable to read-only configuration items. Second, the php. ini file is shared among all applications on the server. Therefore, I don't think application-specific configuration items should be written in this file.

What should I know about the INI file? The most important thing is how to reset the include path to Add configuration items, as shown below.

Listing 3. ini3.php

  

Echo (ini_get ("include_path ")."");

Ini_set ("include_path ",

Ini_get ("include_path"). ":./mylib ");

Echo (ini_get ("include_path ")."");

?>

In this example, I add my local mylib directory to the include path, so I can add the require PHP file from this directory without adding the path to the require statement.

Configuration in PHP

An alternative to storing configuration entries in the INI file is to use a simple PHP script to keep data. The following is an example.

Listing 4. config. php

  

# Specify the location of the temporary directory

#

$ TEMPLATE_DIRECTORY = "tempdir ";

?>

The code for using this constant is as follows.

Listing 5. php. php

  

Require_once 'config. php ';

Function get_template_directory ()

{

Global $ TEMPLATE_DIRECTORY;

Return $ TEMPLATE_DIRECTORY;

}

Echo (get_template_directory ()."");

?>

The code first contains the configuration file (config. php), and then you can directly use these constants.

Using this technology has many advantages. First, if some people only browse the config. php file, the page is blank. Therefore, you can put config. php in the same file and use it as the root of the Web application. Second, it can be edited in any editor, and some editors even have syntax coloring and syntax check functions.

The disadvantage of this technology is that it is a read-only technology like INI files. It is easy to extract data from this file, but it is difficult to adjust the data in this PHP file. in some cases, it is even impossible.

The following alternative method shows how to write a configuration system that is essentially readable and writable.

Text files

The previous two examples are suitable for read-only configuration items, but what about read and write configuration parameters? First, check the text configuration file in listing 6.

Listing 6. config.txt

# My application's configuration file

Title = My App

TemplateDirectory = tempdir

This is the same file format as the INI file, but I have compiled the auxiliary tool myself. To this end, I have created my own Configuration class, as shown below.

Listing 7. text1.php

  

Class Configuration

{

PRivate $ configFile = 'config.txt ';

Private $ items = array ();

Function _ construct () {$ this-> parse ();}

Function _ get ($ id) {return $ this-> items [$ id];}

Function parse ()

{

$ Fh = fopen ($ this-> configFile, 'r ');

While ($ l = fgets ($ fh ))

{

If (preg_match ('/^ #/', $ l) = false)

{

Preg_match ('/^ (.*?) = (.*?) $/', $ L, $ found );

$ This-> items [$ found [1] = $ found [2];

}

}

Fclose ($ fh );

}

}

$ C = new Configuration ();

Echo ($ c-> TemplateDirectory ."");

?>

This code first creates a Configuration object. The constructor then reads config.txt and uses the parsed file content to set the local variable $ items.

The script then looks for TemplateDirectory, which is not directly defined in the object. Therefore, use the $ id set to 'templatedirectory' to call the magic _ get method, __get method returns the value in the $ items array for this key.

This _ get method is specific to the PHP V5 environment, so this script must be run in PHP V5. In fact, all the scripts in this article need to be run in PHP V5.

When you run this script on the command line, you can see the following results:

Http://www.knowsky.com/php.asp

% Php text1.php

Tempdir

%

Everything is expected. the object reads the config.txt file and obtains the correct value for the TemplateDirectory configuration item.

But how should I set a configuration value? Create a new method and some new test code in this class to get this function, as shown below.

Listing 8. text2.php

  

Class Configuration

{

...

Function _ get ($ id) {return $ this-> items [$ id];}

Function _ set ($ id, $ v) {$ this-> items [$ id] = $ v ;}

Function parse (){... }

}

$ C = new Configuration ();

Echo ($ c-> TemplateDirectory ."");

$ C-> TemplateDirectory = 'foobar ';

Echo ($ c-> TemplateDirectory ."");

?>

Now we have a _ set function, which is the "cousin" of The _ get function ". This function does not get a value for a member variable. it is called only when a member variable is set. Set the value of the test code at the bottom and print the new value.

The following is the result of running this code in the command line:

% Php text2.php

Tempdir

Foobar

%

Great! But how can I store it in a file to fix this change? Therefore, you need to write a file and read it. The new function used to write files is as follows.

Listing 9. text3.php

  

Class Configuration

{

...

Function save ()

{

$ Nf = ";

$ Fh = fopen ($ this-> configFile, 'r ');

While ($ l = fgets ($ fh ))

{

If (preg_match ('/^ #/', $ l) = false)

{

Preg_match ('/^ (.*?) = (.*?) $/', $ L, $ found );

$ Nf. = $ found [1]. "=". $ this-> items [$ found [1]. ";

}

Else

{

$ Nf. = $ l;

}

}

Fclose ($ fh );

Copy ($ this-> configFile, $ this-> configFile. '. bak ');

$ Fh = fopen ($ this-> configFile, 'w ');

Fwrite ($ fh, $ nf );

Fclose ($ fh );

}

}

$ C = new Configuration ();

Echo ($ c-> TemplateDirectory ."");

$ C-> TemplateDirectory = 'foobar ';

Echo ($ c-> TemplateDirectory ."");

$ C-> save ();

?>

The new save function cleverly operates config.txt. I did not just rewrite the file with updated configuration items (this will remove the comment), but read the file and flexibly rewrite the content in the $ items array. In this way, the comments in the file are retained.

Run the script on the command line and output the content in the text configuration file. the following output is displayed.

Listing 10. saving function output

% Php text3.php

Tempdir

Foobar

% Cat config.txt

# My application's configuration file

Title = My App

TemplateDirectory = foobar

%

The original config.txt file is now updated by the new value.

Xml configuration file

Although text files are easy to read and edit, they are not as popular as XML files. In addition, XML has many applicable editors that can understand tags, special symbol escaping, and so on. So what is the XML version of the configuration file? Listing 11 shows the configuration file in XML format.

Listing 11. config. xml

  

  

  

   Tempdir

  

Listing 12 shows an updated version of the Configuration class that uses XML to load Configuration settings.

Listing 12. xml1.php

  

Class Configuration

{

Private $ configFile = 'config. XML ';

Private $ items = array ();

Function _ construct () {$ this-> parse ();}

Function _ get ($ id) {return $ this-> items [$ id];}

Function parse ()

{

$ Doc = new DOMDocument ();

$ Doc-> load ($ this-> configFile );

$ Cn = $ doc-> getElementsByTagName ("config ");

$ Nodes = $ cn-> item (0)-> getElementsByTagName ("*");

Foreach ($ nodes as $ node)

$ This-> items [$ node-> nodeName] = $ node-> nodeValue;

}

}

$ C = new Configuration ();

Echo ($ c-> TemplateDirectory ."");

?>

It seems that XML has another advantage: the code is simpler and easier than the text version. To save this XML file, another version of the save function is required to save the result in XML format instead of text format.

Listing 13. xml2.php

...

Function save ()

{

$ Doc = new DOMDocument ();

$ Doc-> formatOutput = true;

$ R = $ doc-> createElement ("config ");

$ Doc-> appendChild ($ r );

Foreach ($ this-> items as $ k => $ v)

{

$ Kn = $ doc-> createElement ($ k );

$ Kn-> appendChild ($ doc-> createTextNode ($ v ));

$ R-> appendChild ($ kn );

}

Copy ($ this-> configFile, $ this-> configFile. '. bak ');

$ Doc-> save ($ this-> configFile );

}

...

This code creates a new XML Document Object Model (DOM) and saves all the data in the $ items array to this Model. After this is done, use the save method to save XML as a file.

Use Database

The final alternative is to use a database to save the value of the configuration element. First, we need to use a simple mode to store configuration data. The following is a simple mode.

Listing 14. schema. SQL

Drop table if exists settings;

Create table settings (

Id mediumint not null AUTO_INCREMENT,

Name TEXT,

Value TEXT,

Primary key (id)

);

This requires some adjustments based on application requirements. For example, if you want to store configuration elements according to each user, you need to add the user ID as an additional column.

To read and write data, I wrote the updated Configuration class as shown in Figure 15.

Listing 15. db1.php

  

Require_once ('Db. php ');

$ Dsn = 'MySQL: // root: passWord @ localhost/config ';

$ Db = & DB: Connect ($ dsn, array ());

If (PEAR: isError ($ db) {die ($ db-> getMessage ());}

Class Configuration

{

Private $ configFile = 'config. XML ';

Private $ items = array ();

Function _ construct () {$ this-> parse ();}

Function _ get ($ id) {return $ this-> items [$ id];}

Function _ set ($ id, $ v)

{

Global $ db;

$ This-> items [$ id] = $ v;

$ Sth1 = $ db-> prepare ('delete FROM settings WHERE name =? ');

$ Db-> execute ($ sth1, $ id );

If (PEAR: isError ($ db) {die ($ db-> getMessage ());}

$ Sth2 = $ db-> prepare (

'Insert INTO settings (id, name, value) VALUES (0 ,?, ? )');

$ Db-> execute ($ sth2, array ($ id, $ v ));

If (PEAR: isError ($ db) {die ($ db-> getMessage ());}

}

Function parse ()

{

Global $ db;

$ Doc = new DOMDocument ();

$ Doc-> load ($ this-> configFile );

$ Cn = $ doc-> getElementsByTagName ("config ");

$ Nodes = $ cn-> item (0)-> getElementsByTagName ("*");

Foreach ($ nodes as $ node)

$ This-> items [$ node-> nodeName] = $ node-> nodeValue;

$ Res = $ db-> query ('select name, value FROM settings ');

If (PEAR: isError ($ db) {die ($ db-> getMessage ());}

While ($ res-> fetchInto ($ row )){

$ This-> items [$ row [0] = $ row [1];

}

}

}

$ C = new Configuration ();

Echo ($ c-> TemplateDirectory ."");

$ C-> TemplateDirectory = 'new Foo ';

Echo ($ c-> TemplateDirectory ."");

?>

This is actually a hybrid text/database solution. Observe the parse method carefully. This class first reads the text file to get the initial value, then reads the database, and then updates the key to the latest value. After setting a value, the key is removed from the database and a new record with updated values is added.

It is interesting to observe how the Configuration class works through multiple versions in this article. it can read data from text files, XML files, and databases, and keep the same interface all the time. I encourage you to use interfaces with the same stability during development. For the client of the object, it is not clear how the task runs. The key is the contract between the object and the client.

What is Configuration and how to configure

Finding an appropriate intermediate point between too many configuration options and insufficient configuration is difficult. It is certain that any database configuration (for example, database name, database user and password) should be configurable. In addition, I have some basic recommended configuration items.

In advanced settings, each feature should have an independent enable/disable option. Allow or disable these options based on their importance to the application. For example, in a Web forum application, the latency feature is enabled by default. However, email notification is disabled by default because it seems to need to be customized.

All user interface (UI) options should be set to one location. The structure of the interface (for example, menu position, additional menu items, URLs linked to specific elements of the interface, logo used, and so on) should all be set to a single position. I strongly recommend that you do not specify font, color, or style entries as configuration items. These settings should be made through Cascading Style Sheet (CSS), and the configuration system should specify which CSS file to use. CSS is an effective and flexible way to set fonts, styles, colors, and so on. There are many outstanding CSS tools that your application should make good use of CSS rather than trying to set standards on its own.

In each feature, I recommend setting 3 to 10 configuration options. These configuration options should be named in a meaningful way. If the configuration options can be set through the UI, the option names in text files, XML files, and databases should be directly related to the title of the interface element. In addition, all these options should have clear default values.

In general, the following options should be configurable: email address, what CSS is used, the location of the system resource referenced from the file, and the file name of the graphic element.

For graphic elements, you may want to create an independent configuration file type named skin, which contains settings for the configuration file, including the position of the CSS file, the position of the image, and these types of things. Then, you can select multiple skin files. This makes it easy to make large-scale changes to the appearance and feeling of the application. This also provides users with an opportunity to change the skin between different product installations. This article does not cover these skin files, but the basic knowledge you have learned here will make it easier to support skin files.

References: If you plan to allow others or companies to use your php application, make sure it is configurable. At least ,...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.