Implementation method of merging ThinkPHP configuration files to eliminate code redundancy

  • 2021-07-09 07:45:22
  • OfStack

Many times when we use ThinkPHP to configure the database connection between the foreground and the background of the website, we often write the configuration separately in the configuration file of the foreground and the configuration file of the background. However, there are many times when the database configuration of foreground and background may be 1-type configuration, but both files are used with 1-type configuration, so the code is redundant at this time.

Website foreground to use the database, such as user registration, user login and comments, etc., these need us in the foreground to use the database, since the use of the database then have to connect to the database! Not to mention the background of the website, the use of databases is everywhere.

Most of the website foreground and background are used in a database, that is, the configuration information of the foreground and background connection database is 1. However, problems have arisen. If you use ThinkPHP, some friends may write the configuration information of connecting to the database in the foreground and background configuration files, that is, config. php files in the Conf folder. At this time, code redundancy is inevitable.

In this case, if the server configuration is changed, both configuration files need to be rewritten, and a slight omission will cause great losses. Therefore, it is necessary to eliminate redundancy and merge configuration files. Specific measures are as follows:

Create a new PHP file under the same level directory as the foreground and background of the website, for example, named config. inc. php, and write the configuration information of the database in this file. The following example:


<?php
return array(
'DB_TYPE=>'mysql',
'DB_NAME'=>'demo',
'DB_HOST'=>'localhost',
'DB_USER'=>'root',
'DB_PWD'=>'123456',
'DB_PREFIX'=>'demo_'
);
?>

Ok, write it in the configuration files of the foreground and background of the website respectively:


<?php
$arr01 = array(
// Other configuration information in the foreground or background 
);
$arr02 = include './config.inc.php';
// Combine this 2 Array of numbers 
return array_merge($arr01,$arr02);
?>

This method can effectively solve the problem of code redundancy. And when changing the database address, just modify the configuration file config. inc. php.


Related articles: