ThinkPHP3.1 Quick Start (1) Basics

Source: Internet
Author: User
Tags constant definition dsn

ThinkPHP is a fast and simple lightweight PHP development framework based on MVC and object-oriented. It complies with the Apache2 open source protocol and has been adhering to simple and practical design principles since its birth, while maintaining excellent performance and simplified code, the system pays special attention to the development experience and ease of use. It also has many original functions and features, providing powerful support for WEB application development.

Directory structure

The latest ThinkPHP version can be downloaded from the official website ( or Github (
Decompress the downloaded compressed file to your WEB directory (or any directory). the directory structure of the Framework is as follows:
Javas── ThinkPHP. php framework entry file
Common‑common Framework Public File
├-Conf framework configuration file
Extended catalog
├ ── Lang core Language Pack directory
├ ── Lib core class library directory
│ Descri── Behavior core Behavior class library
│ ├-Core base class library
│ ├ ── Driver built-in Driver
│ ─ ── Cache built-in Cache driver
│ ─ ── Db built-in database driver
│ ─ ── TagLib built-in label driver
│ └ ── Template built-in Template engine driver
│ └ ── Template built-in Template engine
└ ── Tpl system template directory
Copy code

Note: The public portal file of the Framework is ThinkPHP. php cannot be executed directly. This file can only be called in the project entry file to run properly (as will be discussed later). This is a very easy mistake for many new users.

Portal File

Before you start, you need a Web server and PHP runtime environment, we recommend that you use the integrated development environment WAMPServer (a development kit that integrates Apache, PHP, and MySQL, and supports switching between multiple PHP versions, MySQL versions, and Apache versions) to use ThinkPHP for local development and testing.
Next, create an app subdirectory under the WEB root directory (this app is our project name), create an index. php file under the directory, and add a simple line of code:
<? Php
Require '/ThinkPHP framework directory/ThinkPHP. php ';
Copy code

The role of this line of code is to load ThinkPHP Framework's entry file ThinkPHP. php, which is the first step for all applications developed based on ThinkPHP.
Then, access the entry file in the browser.
Http: // localhost/app/
Copy code

The default file of the Web server is index. php. Therefore, you do not need to add index. php to the URL. After running, we will see the welcome page,

The project directory has been automatically generated. The directory structure is as follows:

─ ── Index. php project portal file ‑common Project Public file directory ‑conf project configuration directory ‑lang project language directory ‑lib project class library directory │ ‑action Action class library directory │ ‑behavior behavior class library directory │ Runtime-Model class library directory │ Runtime-Widget class library directory Runtime-Runtime project directory │ Runtime-Cache template Cache directory │ Runtime-Data Cache directory │ Runtime -Logs log file directory │ └ ── Temp temporary cache directory └ ── Tpl Project template directory

Copy code

If you want the project's entry file to be moved out of the app directory, you only need to modify the index. php content of the entry file:
<? Php
Define ('app _ name', 'app ');
Define ('app _ path', './APP /');
Require '/ThinkPHP framework directory/ThinkPHP. php ';
Copy code

APP_NAME and APP_PATH are used to define the project name and project directory. The project name usually refers to the project directory name.
After moving and modifying the project's entry file, we can
Http: // localhost/
Copy code

Access the app project. Of course, you can also create multiple subdirectories under the Web root directory to deploy multiple projects.

Debugging mode

The running Modes of ThinkPHP include the debugging and deployment modes. By default, ThinkPHP runs in the deployment mode. In deployment mode, the performance is preferred, and as few error messages as possible are thrown. In debugging mode, the priority is given to debugging convenience, and any cache is disabled, and as many error messages as possible are thrown, therefore, it has a certain impact on performance. The deployment mode adopts the project compilation mechanism. During the first operation, the core and project-related files are compiled and cached, after compilation, the configuration files, function files, and database modifications in the development process will be affected (unless you manually clear the cached files under Runtime ). Therefore, to avoid the above problems, we strongly recommend that new users use the debugging mode during ThinkPHP development, so that they can better get error prompts and avoid unnecessary problems and troubles.
To enable the debugging mode, you only need to add a constant definition code at the beginning of the entry file:
<? Phpdefine ('app _ debug', TRUE); // enable the DEBUG mode require '/ThinkPHP framework directory/ThinkPHP. php ';

Copy code

After the development is complete, you can delete the constant definition code or change it:
Define ('app _ debug', false); // disable the debugging mode.
Copy code


Each project has an independent configuration file (Conf/config. php In the project directory). The Definition Format of the configuration file adopts the PHP return array method, for example:
// Project configuration file
Return array ('configuration parameters' => 'configuration value', // more configuration parameters //...);

Copy code

Once necessary, we can add related configuration items in the project configuration file. The add configuration item we mentioned usually refers to adding it to the project configuration file:
'Configuration parameter '=> 'configuration value ',
Copy code

Configuration values can support data including strings, numbers, Boolean values, and arrays. Generally, we recommend that you set parameters in uppercase. If necessary, we can also define other configuration files for the project.


A controller class needs to be defined for each module. The naming rules for the Controller class are as follows:
Module name + Action. class. php (the module name adopts the hump method and the first letter is capitalized)
The default module of the system is Index, and the corresponding controller is Lib/Action/IndexAction. class. php under the project directory. The class name and file name are consistent. The default operation is index, which is a public method of the controller. When the project directory structure is generated for the first time, the system has generated a default controller by default (that is, the welcome page we saw earlier). We will change the index method to the following code:
class IndexAction extends Action {    public function index(){        echo 'hello,world!';    } }

Copy code

The controller must inherit the Action class. A module can contain multiple operation methods. If your operation method is protected or private, you cannot directly access the operation through the URL.

URL request

The portal file is a single portal of the Project. All requests to the project are directed to the portal file of the project. The system will parse the modules and operations of the current request from the URL parameter, the previously accessed URL address does not contain any parameters. Therefore, the system will access the default Index operation of the default module. Therefore, the following access is equivalent to the previous one:
Http: // localhost/app/index. php/Index/index
Copy code

This URL mode is the default PATHINFO mode. Different URL modes have different retrieval modules and operation methods. ThinkPHP supports four URL modes: common Mode, PATHINFO, REWRITE, and compatibility mode.

Normal Mode: the traditional GET parameter passing method is used to specify the currently accessed modules and operations, for example:
Http: // localhost/app /? M = module & a = action & var = value
Copy code

M parameter indicates the module, a operation indicates the operation (the module and the URL parameter name of the operation can be configured), and other GET parameters are described later.

PATHINFO mode: it is the default URL mode of the system and provides the best SEO support. The system has been compatible with the environment, so it can support most host environments. Corresponding to the above URL mode, the URL access address in PATHINFO mode is:
Http: // localhost/app/index. php/module/action/var/value/
Copy code

The first parameter of the PATHINFO Address indicates the module, and the second parameter indicates the operation.
In the PATHINFO mode, URLs can be customized. For example, you can use the following Configuration:
'Url _ PATHINFO_DEPR '=>'-', // modify the PATHINFO parameter delimiter
Copy code

We can also support the following URL access:
Http: // localhost/app/index. php/module-action-var-value/
Copy code

REWRITE mode: This mode adds support for REWRITE Rules Based on the PATHINFO mode. You can remove the entry file index. php In the URL address, but you need to configure additional REWRITE Rules for the WEB server.
For Apache, you must add the. htaccess file at the same level as the entry file. The content is as follows:
<IfModule mod_rewrite.c>RewriteEngine onRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] </IfModule>

Copy code

Next, you can use the following URL to access:
Http: // localhost/app/module/action/var/value/
Copy code

Compatibility mode: This mode is used in special environments that do not support PATHINFO. The URL address is:
Http: // localhost/app /? S =/module/action/var/value/
Copy code

The compatibility mode works with the Web server REWRITE rule definition to achieve the same URL effect as the REWRITE mode.


ThinkPHP has a built-in compiled template engine and supports native PHP templates. It also provides template engine drivers including Smarty. Unlike Smarty, if ThinkPHP does not specify a template when rendering the template, it will adopt the default positioning rules of the system. The definition specification is Tpl/Module name/operation name .html. Therefore, the default template file for Index operations of the index module is located in Tpl/Index/index.html under the project directory.
For example:

Copy code

To output a view, you must perform the template rendering and output operations in the Controller method. For example:
Class IndexAction extends Action {
Public function index (){
$ This-> name = 'thinkphp'; // assign values to template Variables
$ This-> display ();
Copy code

No template is specified in the display method, so the Index/index.html template file is output according to the default system rules.
Next, enter
Http: // localhost/app/
Copy code

Output in the browser
Hello, thinkphp!

Read data

Before starting, create a think_data table in the database thinkphp (take mysql database as an example ):
CREATE TABLE IF NOT EXISTS `think_data` (  `id` int(8) unsigned NOT NULL AUTO_INCREMENT,  `data` varchar(255) NOT NULL,  PRIMARY KEY (`id`) ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;INSERT INTO `think_data` (`id`, `data`) VALUES (1, 'thinkphp'), (2, 'php'), (3, 'framework');

Copy code

To read data from the database, add the following database connection information to the project configuration file:
// Add database configuration information
'Db _ type' => 'mysql', // Database TYPE
'Db _ host' => 'localhost', // server address
'Db _ name' => 'thinkphp', // Database NAME
'Db _ user' => 'root', // USER Name
'Db _ pwd' => '', // Password
'Db _ port' => 3306, // PORT
'Db _ prefix' => 'think _ ', // database table PREFIX
Copy code

Or use the following Configuration:
'Db _ DSN '=> 'mysql: // root @ localhost: 3306/thinkphp'
Copy code

You can use DB_DSN to define configuration parameters. The DSN parameter format is as follows:
Database Type: // User name: password @ database address: Database port/Database Name
If both configuration parameters exist, DB_DSN configuration parameters take precedence.

Next, modify the Controller method and add the code for reading data:
Class IndexAction extends Action {public function index () {$ Data = M ('data '); // instantiate the Data data Model $ this-> Data = $ Data-> select (); $ this-> display ();}}

Copy code

The M function is used here as the built-in instantiation Model Method of ThinkPHP, and the corresponding model class does not need to be created to instantiate the model using the M method, you can understand that the M method operates the underlying Model class directly, and the Model class has the basic CURD operation method.
After M ('data') is instantiated, you can perform operations (including CURD) on the think_data table (think _ is the Data table prefix defined in the project configuration file, the usage of M functions is much more advanced.
After the controller is defined, modify the template file and add the data output tag as follows:

Copy code

The volist tag is the tag used by the built-in template engine to output the dataset. The usage of {$ vo. id} and {$ vo. data} is similar to that of Smarty. It is the field used to output data. Here, it indicates the id of the output think_data table and the value of the data field.
We access
Http: // localhost/app/
Copy code

1 -- thinkphp
2 -- php
3 -- framework
Copy code

If an error occurs, check whether debugging mode is enabled or the cached files under the Runtime directory are cleared.
If you see the output above, congratulations! You have obtained the ThinkPHP key!


In this article, we learned about ThinkPHP's directory structure and URL mode, how to create the project's entry file and enable the debugging mode, as well as the basic understanding of controllers, templates, and models, we will continue to learn about the data CURD operations later.

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