How to build PHP programs with different files _php tutorial

Source: Internet
Author: User
Tags configuration settings dsn pear

How to build PHP programs with different files


The following is the referenced content:

If you plan to make your PHP application available to someone else or company, you need to make sure that the program is configurable. At a minimum, allow the user to set the database login and password in a secure manner so that the material in it is not publicly available.

This article shows several techniques for storing configuration settings and editing these settings. In addition, the article also provides guidance on which elements need to be configured and how to avoid getting bogged down in configuration or under-provisioning.

Configuring using the INI file

PHP has built-in support for configuration files. This is achieved through the initialization file (INI) mechanism of the php.ini file, where constants such as database connection timeouts or how sessions are stored are defined in the php.ini file. If you prefer, you can customize the configuration for your application in this php.ini file. To illustrate, I add the following line of code to the php.ini file.

Myapptempdir=foo

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

Listing 1. ini1.php

  

function Get_template_directory ()

{

$v = Get_cfg_var ("Myapptempdir");

return ($v = = null)? "TempDir": $v;

}

Echo (Get_template_directory (). ” );

?>

When you run this code on the command line, you get the following result:

% PHP ini1.php

Foo

%

That's great. But why not use the standard INI function to get the value of a Myapptempdir configuration item? I researched it and found that in most cases, custom configuration items cannot be obtained using these methods. However, using the Get_cfg_var function can be accessed.

To make this method simpler, the access to the variable is encapsulated in the second function, which 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, so if you want to use a different mechanism or store the INI file in another location, you don't have to make a lot of effort to change a large number of functions.

I do not recommend using the INI file as an application configuration for two reasons. First, although it is easier to read the INI file, it is almost impossible to write the INI file safely. So this is only appropriate for read-only configuration items. Second, the php.ini file is shared on all applications on the server, so I think the application-specific configuration item should not be written in the file.

What do I need to know about 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 case, I added my local mylib directory to the include path, so I was able to require the PHP file from that directory without adding the path to the Require statement.

Configuration in PHP

A common alternative to storing configuration entries in the INI file is to use a simple PHP script to persist the data. Here is a sample.

Listing 4. config.php

  

# Specify the location of the temporary directory

#

$TEMPLATE _directory = "TempDir";

?>

The code that uses the constant is shown below.

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 use the constants directly.

There are many advantages to using this technology. First, if some people just browse the config.php file, the page is blank. So you can put config.php in the same file and act as the root of the WEB application. Second, it can be edited in any editor, and even has syntax coloring and grammar checking in some editors.

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

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

Text file

The previous two examples are appropriate for read-only configuration entries, but what about the read-write configuration parameters? First, take a look at 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 written the accessibility tool myself. To do this, I 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. " ” );

?>

The code first creates a Configuration object. The constructor then reads Config.txt and sets the local variable $items with the parsed file contents.

The script then looks for templatedirectory, which is not defined directly in the object. Therefore, using the $id set to ' Templatedirectory ' to invoke the magical __get method, the __get method returns the value in the $items array for that key.

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

When you run this script at 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 then obtains the correct value for the Templatedirectory configuration item.

But what do you do with setting a configuration value? This function can be obtained by creating a new method and some new test code in this class, 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, with a __set function, it is the "cousin" of the __get function. The function does not get a value for a member variable, which is called when a member variable is to be set. The test code at the bottom sets the value and prints out the new value.

Here's what happens when you run this code on the command line:

% PHP text2.php

TempDir

Foobar

%

That's great! But how can you store it in a file so that the change will be fixed? To do this, you need to write the file and read it. The new function for writing the file, as shown below.

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 the config.txt. Instead of overwriting the file with the updated configuration item (which removes the comment), I read the file and flexibly rewrite the contents of the $items array. In this case, the comments in the file are preserved.

You can see the following output when you run the script on the command line and output the contents of the text configuration file.

Listing 10. Save 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 with 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 a number of applicable editors that can understand tags, special symbol escapes, 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.

  

  

  

   TempDir

  

Listing 12 shows an updated version of the configuration class that uses XML to mount the config settings.

Listing 12. xml1.php

  

Class Configuration

{

Private $configFile = ' config + ';

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. " ” );

?>

There seems to be another benefit to XML: The code is more concise and easier than the text version of the code. To save this XML, another version of the Save function is required to save the results 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 (Document Object model, DOM), and then saves all the data in the $items array into this model. After you have done this, use the Save method to save the XML as a file.

Working with databases

The last alternative is to use a database to hold the value of the configuration element. The first thing to do is to store the configuration data in a simple pattern. The following is a simple pattern.

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 the application requirements. For example, if you want the configuration element to be stored per user, you need to add the user ID as an additional column.

To read and write the data, I wrote the updated Configuration class shown in 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 + ';

Private $items = Array ();

function __construct () {$this->parse ();}

function __get ($id) {return $this->items[$id];}

function __set ($id, $v)

{

Global $db;

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

$sth 1 = $db->prepare (' DELETE from Settings WHERE name=? ');

$db->execute ($sth 1, $id);

if (Pear::iserror ($db)) {die ($db->getmessage ());}

$sth 2 = $db->prepare (

' INSERT into settings (ID, name, value) VALUES (0,?,?) ');

$db->execute ($sth 2, 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 mixed text/database solution. Please observe the parse method carefully. The class first reads the text file to get the initial value, and then reads the database, updating the key to the most recent value. After setting a value, the key is removed from the database and a new record with the updated value is added.

It is interesting to see how the Configuration class works with multiple versions of this article, which can read data from text files, XML, and databases, and always maintain the same interface. I encourage you to use interfaces with the same stability in development as well. For an object's client, the specifics of how this work is run are ambiguous. The key is the contract between the object and the client.

What is configuration and how to configure it

Finding an appropriate intermediate point between configuring too many configuration options and insufficient configuration is a difficult thing to do. To be sure, 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 a separate enable/disable option. These options are allowed or disabled based on their importance to the application. For example, in a WEB forum application, the delay attribute is enabled by default. But e-mail notifications are disabled by default, as this seems to require customization.

The user interface (UI) options should all be set to a single location. The structure of the interface (for example, menu location, additional menu items, URLs linked to specific elements of the interface, logos used, etc.) should all be set to a single location. I strongly recommend that you do not specify font, color, or style entries as configuration items. These should be set by cascading style sheets (cascading style sheets,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 great CSS tools, and your application should make good use of CSS, rather than trying to set standards yourself.

In each of these features, I recommend setting 3 to 10 configuration options. These configuration options should be named in a way that is significant. If the configuration options can be set through the UI, the name of the option in the text file, XML file, and database should be directly related to the title of the interface element. In addition, these options should all have explicit default values.

In general, the following options should be configurable: e-mail addresses, what CSS uses, the location of system resources referenced from files, and the file names of graphic elements.

For graphical elements, you might want to create a separate profile type called skin that contains settings for the configuration file, including the location of the CSS file, the location of the graphic, and these types of things. Then, let the user choose among a variety of skin files. This makes it easy to make large-scale changes to the look and feel of your application. This also gives the user an opportunity to replace the skin between different product installations. This article does not cover these skin files, but the basics you learn here will make it easier to support your skin files.

http://www.bkjia.com/PHPjc/950760.html www.bkjia.com true http://www.bkjia.com/PHPjc/950760.html techarticle How to build PHP programs in different files The following is the referenced content: If you plan to let someone else or company use your PHP application, you need to make sure that the program is configurable. At least, ...

  • 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.