ThinkPHP3.1 basic knowledge Quick Start

Source: Internet
Author: User
Tags constant definition

Among today's many MVC frameworks, 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 is released, since its birth, it has been adhering to the concise and practical design principles. While maintaining excellent performance and simplified code, it pays special attention to the development experience and ease of use, and has many original functions and features, it provides powerful support for WEB application development. Is the first choice for many PHP developers. This article briefly describes ThinkPHP3.1 basic knowledge.

1. directory structure

The latest ThinkPHP version can be downloaded from the official website (http://thinkphp.cn/down/framework.html) or Github (https://github.com/liu21st/thinkphp/downloads.
Decompress the downloaded compressed file to your WEB directory (or any directory). the directory structure of the Framework is as follows:

├ ── ThinkPHP. php framework entry file ‑common Framework Public file ‑conf framework configuration file ‑extend framework extension directory ‑lang core Language Pack directory ‑lib core class library directory │ Behavior-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

Note: The public portal file of the frameworkThinkPHP. phpIt 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.

2. Entry 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 ';

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/

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

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:

<? Phpdefine ('app _ name', 'app'); define ('app _ path ','. /app/'); require'/ThinkPHP framework directory/ThinkPHP. php ';

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/

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

3. 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 ';

After the development is complete, you can delete the constant definition code or change it:

Define ('app _ debug', false); // disable the debugging mode.


4. Configuration

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:

// Return array ('configuration parameters' => 'configuration value', // more configuration parameters //...);

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 ',

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.

5. Controller

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!'; } }

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.

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

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:That is, 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

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/

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

We can also support the following URL access:

http://localhost/app/index.php/module-action-var-value/

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>

Next, you can use the following URL to access:

http://localhost/app/module/action/var/value/

Compatibility mode:Is used in a special environment that does not support PATHINFO. The URL address is:

http://localhost/app/?s=/module/action/var/value/

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

7. View

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:

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 a value to the template variable $ this-> display ();}}

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/

Output in the browser

hello,thinkphp!

8. 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');

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 ', // The server address 'db _ name' => 'thinkphp', // The Database NAME 'db _ user' => 'root ', // username 'db _ pwd' => '', // password 'db _ port' => 3306, // PORT 'db _ prefix' => 'think _', // database table prefix

Or use the following Configuration:

'DB_DSN' => 'mysql://root@localhost:3306/thinkphp'

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 ();}}

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:

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/

Output

1--thinkphp2--php3--framework

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, you have mastered the basic ThinkPHP basics!

Summary:

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 basics of controllers, templates, and models.

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.