Home >Backend Development >PHP Tutorial >How to merge ThinkPHP configuration files to eliminate code redundancy, _PHP tutorial
Many times when we use ThinkPHP to configure the database connections between the front-end and back-end of the website, we often write configurations in the front-end configuration file and the back-end configuration file separately. However, there are many times when the front-end and back-end databases may have the same configuration, but the same configuration is used in both files, so the code becomes redundant.
It is best to use a database at the frontend of the website, such as user registration, user login, and comments, etc. These all require us to use the database at the frontend. Since we use the database, we must connect to the database! Not to mention the backend of the website, databases are used everywhere.
Most websites use a database in the frontend and backend, that is, the configuration information for connecting to the database in the frontend and backend is the same. However, a problem arises. When using ThinkPHP, some friends may have written the configuration information for connecting to the database in the front-end and back-end configuration files, that is, the config.php file 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. A slight oversight will cause heavy losses. In this regard, it is necessary to eliminate redundancy and merge configuration files. The specific measures are as follows:
Create a new PHP file in the same directory as the frontend and backend of the website, for example, name it: config.inc.php, and write the database configuration information in this file. Example below:
<?php return array( 'DB_TYPE=>'mysql', 'DB_NAME'=>'demo', 'DB_HOST'=>'localhost', 'DB_USER'=>'root', 'DB_PWD'=>'123456', 'DB_PREFIX'=>'demo_' ); ?>
Okay, write this in the configuration files of the website’s frontend and backend respectively:
<?php $arr01 = array( //前台或后台其他的配置信息 ); $arr02 = include './config.inc.php'; //组合这二个数组 return array_merge($arr01,$arr02); ?>
Using this method can effectively solve the problem of code redundancy. And when changing the database address, you only need to modify the configuration file config.inc.php.