ThinkPHP3.1 Basic Knowledge QuickStart _php Instance

Source: Internet
Author: User
Tags constant definition mysql version php framework

In today's numerous MVC frameworks, thinkphp is a fast, simple MVC and object-oriented lightweight PHP development framework that follows the release of the Apache2 Open source protocol, and has been adhering to simple and practical design principles since its inception, while maintaining outstanding performance and Simplicity Code Especially focus on development experience and ease of use, and has a number of original features and features, for Web application development provides a strong support. is the first choice for many PHP developers. This paper makes a brief introduction to ThinkPHP3.1 basic knowledge.

1. Directory structure

The latest version of thinkphp can be downloaded from the official website (http://thinkphp.cn/down/framework.html) or GitHub (https://github.com/liu21st/thinkphp/downloads).
Unzip the downloaded compressed file to your Web directory (or any directory), and the framework's directory structure is:

├─thinkphp.php Framework Portal File
 ├─common Framework common file
 ├─conf Framework Profile
 ├─extend Framework extension directory
 ├─lang core Language Pack directory
 ├─lib core Class Library Directory
 │├─behavior core Behavior Class library
 │├─core Core base Class library
 │├─driver built-in driver
 ││├─cache built-in cache driver
 ││├─db built-in database driver
 ││├─t Aglib built-in tag driver
 ││└─template built-in template engine driver
 │└─template built-in template engine
 └─TPL system template Directory

Note that the framework's public portal file, thinkphp.php , cannot be executed directly , and it can only be invoked in the project entry file to function correctly (as we'll see later), which is a mistake that many beginners make easily.

2. Entry file

Before you start, you need a Web server and PHP runtime environment, and if you haven't, we recommend using the Integrated development environment Wampserver (a development kit that integrates Apache, PHP, and MySQL, and supports multiple PHP versions, MySQL version and the Apache version of the switch) to use thinkphp for local development and testing.
Next we create an app subdirectory under the Web root directory (this app is our project name), and then create a index.php file under that directory and add a simple line of code:

<?php
 require '/thinkphp framework directory/thinkphp.php ';

The purpose of this line of code is to load the thinkphp framework's Portal file thinkphp.php, which is the first step in all thinkphp development applications.
Then, access the portal file in the browser.

http://localhost/app/

The default file for a generic Web server is index.php, so we don't need to add index.php to the URL address. After running, we will see the Welcome page,

The project directory is automatically generated and the directory structure is as follows:

├─index.php Project Entry file
 ├─common project common 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
 │├─model model class Library directory
 │└─widget Widget class Library directory
 ├─runtime Project runtime directory
 │ ├─cache Template Cache directory
 │├─data data cache directory
 │├─logs log file directory
 │└─temp temporary cache directory
 └─TPL project template directory

If you want the entry file for the project to be moved outside the app directory, just modify the entry file index.php to read:

<?php
define (' app_name ', ' APP ');
Define (' App_path ', './app/');
 Require '/thinkphp framework directory/thinkphp.php ';

The App_name and App_path divisions are used to define the project name and project directory, which usually refers to the directory name of the project.
After moving and modifying the entry file for the project, we can

http://localhost/

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

3. Debug mode

The thinkphp operating mode includes debug mode and deployment mode, which is run under Deployment mode by default. Performance takes precedence in the deployment mode and throws as little error information as possible, debug mode takes precedence over errors, closes any cache, and throws as many error messages as possible, so it has a certain impact on performance. The deployment pattern uses a project compilation mechanism, which is compiled to cache core and project-related files for the first time, because it affects the effectiveness of configuration files, function files, and database modifications during development (unless you manually empty the cached files below runtime after you modify them). Therefore, in order to avoid the above problems, we strongly recommend that the Novice in the use of thinkphp development process using debug mode, so that you can better get the error message and avoid unnecessary problems and troubles.
Opening debug mode is simple, we just need to add a line of constant definition code at the beginning of the entry file:

<?php
define (' App_debug ', TRUE);//Open debug mode
 require '/thinkphp framework directory/thinkphp.php ';

Once the development is complete, when we actually do the project deployment, delete the line constant definition code, or change to:

Define (' App_debug ', false); Turn off debug mode


4. Configure

Each project has a separate configuration file (conf/config.php in the project directory), and the configuration file is defined in a way that PHP returns an array, for example:

Project Profile return
 Array (
 ' configuration parameter ' => ' config value ', 
 //More configuration Parameters//...
 );

Once necessary, we can add related configuration items to the project configuration file. Typically, the add configuration item that we refer to is added to the project configuration file:

' Configuration parameter ' => ' configuration value ', 

Configuration values can support data that includes strings, numbers, Boolean values, and arrays, and usually we recommend that the configuration parameters use uppercase definitions. If necessary, we can also define additional configuration files for the project.

5. Controller

You need to define a controller class for each module, and the naming specification for the controller class is:
Module name +action.class.php (the module name is the Hump method and the first letter is capitalized)
The default module of the system is index, the corresponding controller is the lib/action/indexaction.class.php under the project directory, the class name and file name are the same. The default action is index, which is a public method of the controller. When the project directory structure was first generated, the system had generated a default controller by default (the Welcome page that was previously seen), and we changed the index method to the following code:

Class Indexaction extends Action {public
 function index () {
 echo ' hello,world! ';
 }
 }

The controller must inherit the action class, and a module can include multiple action methods. If your method of operation is protected or private type, you cannot access the operation directly through the URL.

6.URL Request

The entry file is a single entry for the project, all requests to the project are directed to the project's entry file, the module and operation of the current request are parsed from the URL parameter, and the URL address that we visited previously has no parameters, so the system accesses the default action (index) of the default module. So the following access is equivalent to the previous one:

Http://localhost/app/index.php/Index/index

This kind of URL pattern is the system default PathInfo mode, different URL mode gets the module and the operation method is different, the thinkphp supports the URL pattern to have four kinds: normal mode, pathinfo, rewrite and compatibility mode.

Normal Mode: the traditional get-pass method to specify the modules and operations currently accessed, for example:

Http://localhost/app/?m=module&a=action&var=value

The M parameter represents the module, and a action represents the action (the URL parameter name of the module and operation is configurable), followed by the other get parameters.

pathinfo Mode: is the system's default URL mode, provides the best SEO support, the system has done a compatible environment, so can support most host environment. Corresponding to the URL pattern above, the URL access address under PathInfo mode is:

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

The first parameter of the PathInfo address represents the module, and the second parameter represents the operation.
Under PathInfo mode, URLs are customizable, for example, through the following configuration:

' Url_pathinfo_depr ' => '-',//change pathinfo parameter separator

We can also support the following URL access:

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

Rewrite mode: is to add the support of rewrite rules on the basis of PathInfo mode, can remove the entry file index.php in the URL address, but need to configure the Web server rewrite rules.
If it is Apache, you need to add the. htaccess file at the same level as the entry file:

<ifmodule mod_rewrite.c>
rewriteengine on
rewritecond%{request_filename}!-d
Rewritecond%{ Request_filename}!-f
rewriterule ^ (. *) $ index.php/$1 [qsa,pt,l]
 </IfModule>

Next, you can access the following URL address:

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

compatibility mode: is for special environments that do not support pathinfo, the URL address is:

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

Compatibility mode with the definition of Web server rewrite rules, you can achieve the same URL effect as the rewrite mode.

7. View

Thinkphp has a built-in build template engine, also supports native PHP templates, and also provides template engine drivers including smarty. Unlike Smarty, thinkphp does not specify a template when the template is rendered, the system default positioning rule is used, and the definition specification is the tpl/module name/operation name. html, so the default template file for the index operation of the index module is located under the project directory tpl/ Index/index.html.
For example:

 
 

To output a view, you must perform a template render output operation in the Controller method, for example:

Class Indexaction extends Action {public
 function index () { 
 $this->name = ' thinkphp ';//Make template variable assignment
 $ This->display ();
 }
 

We did not specify any templates in the display method, so we output the index/index.html template file according to the system default rules.
Next, we enter in the browser

http://localhost/app/

The browser will output

hello,thinkphp!

8. Reading data

Before we start, we first create a think_data datasheet in the database thinkphp (take the MySQL database for example):

CREATE TABLE IF not EXISTS ' think_data ' (
 ' id ' int (8) unsigned not NULL auto_increment,
 ' data ' varchar (255) Not NU LL,
 PRIMARY KEY (' id ')
 ) Engine=myisam DEFAULT Charset=utf8;
INSERT into ' think_data ' (' id ', ' data ') VALUES
 (1, ' thinkphp '),
 (2, ' php '),
 (3, ' framework ');

If we need to read the data in the database, we need to add the database connection information in the project configuration file as follows:

Add Database configuration information
 ' db_type ' => ' mysql ',//database type
 ' db_host ' => ' localhost ',//server address
 ' db_name ' => ' thin Kphp ',//database name
 ' Db_user ' => ' root ',//user name
 ' 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 '

Use the Db_dsn method definition to simplify configuration parameters, and the DSN parameter format is:
Database type://Username: password @ database address: Database Port/Database name
If both configuration parameters are present, the DB_DSN configuration parameter takes precedence.

Next, we modify the next controller method to add code to read the data:

Class Indexaction extends Action {public
 function index () {
 $Data = M (' data ');//Instantiate the data model
 $this->data = $Data->select ();
 $this->display ();
 }
 

Here the M function is used, is the thinkphp built-in instantiation model method, and the M method instantiation model does not need to create the corresponding model class, you can understand that the M method is directly at the bottom of the model class, and model class has the basic curd operation method.
M (' data ') is instantiated, the Think_data data table (THINK_ is the table prefix we defined in the project configuration file) can be manipulated (including curd), and the M function has a lot of usage, which we'll learn more about later.
After defining the controller, we modify the template file and add the data output label as follows:

 
 

The Volist label is the label that the built-in template engine uses to output the dataset. {$vo. ID} and {$vo. Data} are similar in usage to Smarty, which is the field used to output data, which represents the ID of the output think_data table and the value of the data field.
Our visit

http://localhost/app/

Will output

1--thinkphp
2--php
3--framework

If an error occurs, check to see if you have turned on debug mode or empty the cached file under the runtime directory.
If you see the output above, then you have mastered the basic knowledge of thinkphp!

Summarize:

In this article we learned about the thinkphp directory structure, URL patterns, how to create entry files for projects and open debug 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.