ThinkPHP3.1 Basic Knowledge QuickStart _php instances

Source: Internet
Author: User
Tags constant definition php framework
In today's numerous MVC frameworks, thinkphp is a fast, simple MVC-based and object-oriented lightweight PHP development framework that follows the Apache2 Open source protocol, and has been adhering to simple and practical design principles since its inception, while maintaining excellent performance and simplicity of code. In particular, it focuses on the development experience and ease of use, and has many original features and features that provide strong support for Web application development. is the preferred choice for many PHP developers. This article is a brief introduction to ThinkPHP3.1 basic knowledge.

1. Directory structure

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

├─thinkphp.php Framework Portal File ├─common Framework common file ├─conf Framework configuration file ├─extend Framework Extensions directory ├─lang Core Language Pack directory ├─lib core class library directory │├─behavior core behavior class library │├─co Re core base Class library │├─driver built-in driver ││├─cache built-in cache driver ││├─db built-in database driver ││├─taglib built-in tag driver ││└─template built-in template engine driven │└─template built-in template Engine └─TPL System Template Directory

Note that the public portal file thinkphp.php of the framework cannot be executed directly , and the file can only be called in the project portal file in order to function properly (as described later), which is a mistake many novice users can easily make.

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 Apache version of the switch) to use thinkphp for local development and testing.
Next we create an app subdirectory below the Web root directory (the app is our project name), then create a index.php file underneath the 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-based development applications.
Then, access the portal file in the browser.

http://localhost/app/

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

And the project directory has been automatically generated, the directory structure is as follows:

├─index.php Project portal File ├─common project Common Files directory ├─conf project configuration directory ├─lang Project language directory ├─lib Project class Library directory │├─action Action class Library directory │├─behavior behavior Class library catalog │ ├─model Model Class Library directory │└─widget Widget class Library Directory ├─runtime project run-time catalog │├─cache template cache directory │├─data data cache directory │├─logs log file directory │└─temp temporary cache directory └─ TPL Project Template Catalog

If you want the entry file for the project to be moved outside the app directory, you only need to modify the contents of the Portal file index.php:

<?phpdefine (' app_name ', ' APP ');d efine (' App_path ', './app/'); Require '/thinkphp framework directory/thinkphp.php ';

The App_name and App_path subsections are used to define the project name and project directory, which typically refers to the project's directory name.
After moving and modifying the project's entry file, we can

http://localhost/

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

3. Debug mode

The run mode of thinkphp includes debug mode and deployment mode, which is run under Deployment mode by default. Performance takes precedence over the deployment pattern and throws as little error information as possible, while debug mode takes precedence over errors, shuts down any caches, 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 compiles the core and project-related files for the first run, because the compilation affects the configuration files, function files, and database modifications during development (unless you manually empty the cache files under 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 of the use of debugging mode, so that you can better get error hints and avoid some unnecessary problems and worries.
Turning on debug mode is simple, we just need to add a line of constant definition code at the beginning of the portal file:

<?phpdefine (' App_debug ', TRUE); Open debug mode require '/thinkphp frame is located in the directory/thinkphp.php ';

After the development is complete, when we actually deploy the project, delete this line of constant definition code, or change to:

Define (' App_debug ', false); To turn off debug mode


4. Configuration

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

Project configuration file return Array (' configuration parameters ' = = ' configuration value ',  //More configuration Parameters//...);

Once necessary, we can add related configuration items to the project configuration file. The addition of configuration items that we refer to usually refers to adding in the project configuration file:

Configuration values can support data including strings, numbers, Boolean values, and arrays, and generally we recommend that the configuration parameters be defined with uppercase. If necessary, we can also define additional configuration files for the project.

5. Controller

A controller class needs to be defined for each module, and the naming convention for the Controller class is:
Module name +action.class.php (the module name uses the Hump method and the first letter capitalization)
The default module for the system is index, and the corresponding controller is the lib/action/indexaction.class.php under the project directory, with the class name and file name consistent. The default action is index, which is a public method for the controller. When the project directory structure was first generated, a default controller was generated by default (that is, the Welcome page you saw earlier), 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 action method is protected or private type, you cannot access the operation directly through the URL.

6.URL Request

The portal file is a single entry for the project, and all requests to the project are directed to the project's portal file, which resolves the current request's module and operation from the URL parameter, without any parameters in the URL address we visited previously, so the system accesses the default action (index) of the default module (index), 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 pattern obtains the module and the operation method different, the thinkphp supports the URL pattern to have four kinds: normal mode, PATHINFO, rewrite and compatibility mode.

Normal Mode: the traditional Get method to specify the modules and operations that are currently accessed, such as:

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

The M parameter represents the module, a operation that 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 the environment compatible processing, so it can support the majority of 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 delimiter

We can also support the following URL access:

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

Rewrite mode: is based on the PathInfo mode to add the support of rewrite rules, you can remove the URL address inside the entry file index.php, but need to configure additional Web server rewrite rules.
If it is Apache, you will need to add the. htaccess file to the sibling of the portal file with the following content:

 
  
   
  Rewriteengine Onrewritecond%{request_filename}!-drewritecond%{request_filename}!-fRewriteRule ^ (. *) $ index.php/$1 [Qsa,pt,l] 
 
  

Next, you can access it using the following URL address:

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

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

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

Compatibility mode, in conjunction with the definition of a Web server rewrite rule, can achieve the same URL effect as rewrite mode.

7. View

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

  Hello {$name}   Hello, {$name}!  

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 ';//template variable assignment $this->display (); } }

We did not specify any templates in the display method, so the index/index.html template file was exported 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 begin, we first create a think_data data table in the database thinkphp (for example, MySQL database):

CREATE TABLE IF not EXISTS ' think_data ' (' id ' int (8) unsigned not NULL auto_increment, ' data ' varchar (255) is not NULL, PRIM ARY 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 ' = ' thinkphp ',//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 '

The configuration parameters can be simplified using the Db_dsn method definition, and the DSN parameter format is:
Database type://user name: password @ Database address: Database Port/Database name
If both configuration parameters are present, the DB_DSN configuration parameter takes precedence.

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

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

The M function is used here, which is the method of thinkphp the built-in instantiation model, and the M method instantiation model does not need to create the corresponding model class, you can understand that the M method is the model class directly in the operation, and the model class has the basic curd operation method.
Once M (' data ') is instantiated, it is possible to manipulate the Think_data data table (THINK_ is the data table prefix that we defined in the project configuration file) (including curd), and there are many uses of the M function, which we will look into later.
After defining the controller, we modify the template file and add the data output tag as follows:

  Select Data   
 
  
   
   {$vo. id}--{$vo. Data}
  
   

The volist tag is a label used by the built-in template engine to output datasets. {$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.
US to visit

http://localhost/app/

Will output

1--thinkphp2--php3--framework

If an error occurs, check whether you have opened debug mode or emptied the cache file under the runtime directory.
If you see the above output, then you have mastered the basics of getting started with thinkphp!

Summarize:

In this article we have learned about the thinkphp directory structure, URL patterns, how to create entry files for a project and open debug mode, as well as a basic understanding 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.