ThinkPHP3.1 Quick Start (1) Basic _php Tutorial

Source: Internet
Author: User
Tags constant definition php framework

Brief introduction


Thinkphp is a fast, easy-to-use MVC 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 minimalist code, with a particular focus on development experience and ease of and has a lot of original features and features, for Web application development provides a strong support.

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 Entry File
├─common Framework Public File
├─conf Framework Configuration file
├─extend Framework Extensions 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
││├─taglib built-in label driver
││└─template built-in template engine driver
│└─template built-in template engine
└─TPL System Template Directory
Copy Code

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.

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:
Require '/thinkphp framework directory/thinkphp.php ';
Copy Code

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/
Copy Code

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 catalog │  ├─action Action class Library │  ├─behav IOR Behavior Class Library catalog │  ├─model Model Class library catalog │  └─widget Widget Class library catalog ├─runtime Project runtime Catalog │  ├─cache Template Cache directory │  ├─data data Cache directory │
  
   ├─logs log file directory │  └─temp temporary cache directory └─TPL project template directory
  

Copy Code

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:
Define (' App_name ', ' APP ');
Define (' App_path ', './app/');
Require '/thinkphp framework directory/thinkphp.php ';
Copy Code

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/
Copy Code

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

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:
 
Copy Code

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
Copy Code


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 '     = = ' config value ',     //More configuration Parameters//    ...);

Copy Code

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:
' Config parameter ' = ' config value ',
Copy Code

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.

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

Copy Code

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.

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
Copy Code

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
Copy Code

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/
Copy Code

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
Copy Code

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

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] 
 
   

Copy Code

Next, you can access it using the following URL address:
http://localhost/app/module/action/var/value/
Copy Code

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/
Copy Code

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

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

Copy Code

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 '; Assigning a template variable
$this->display ();
}
}
Copy Code

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/
Copy Code

The browser will output
hello,thinkphp!

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) Not NU LL,  PRIMARY KEY (' id ')) engine=myisam  DEFAULT Charset=utf8; INSERT into ' think_data ' (' id ', ' data ') VALUES (1, ' t Hinkphp '), (2, ' php '), (3, ' framework ');

Copy Code

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:
Adding 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 ' and ' = ',//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

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->select ();        $this->display ();    } }

Copy Code

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}
  
    

Copy Code

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/
Copy Code

Will output
1--thinkphp
2--php
3--framework
Copy Code

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, congratulations you've got the key to getting started thinkphp!

Summarize

In this article we have learned about Thinkphp's 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, and continue to understand curd operations on data.

http://www.bkjia.com/PHPjc/446943.html www.bkjia.com true http://www.bkjia.com/PHPjc/446943.html techarticle Introduction 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 the simple and practical design principles since its inception ...

  • Related Article

    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.