The end of the thinkphp 5.* far more than that.

Source: Internet
Author: User
Tags dsn git clone

Directory
Download install
Specification Grooming
Structure Introduction
Simple configuration
Simple data display
Database configuration
Database basic use
Model Basic Use
Summary: (thinkphp5.+<--> thinkphp3.+)
Download install
First, download the installation of the official website
There are many ways to get thinkphp, and the official web site (http://thinkphp.cn) provides a stable version or a download with the full version of the extension. The download version of the
official website is not necessarily the latest version, and the Git version gets the version that is kept updated.
Two, Composer installation
ThinkPHP5 support the use of Composer installation, if you have not installed Composer, you can follow the method of Composer installation. In Linux and Mac OS X, you can run the following command:
curl-ss https://getcomposer.org/installer | php
MV composer.phar/usr/local/bin/compo Ser
in Windows, you need to download and run Composer-setup.exe.
then under the command line, switch to your Web root and execute the following command:
composer Create-project Topthink/think tp5--prefer-dist
Composer Update method: Composer Self-update
Three, git install
If you don't know composer well or feel composer too slow, you can also use Git repository to install and update, ThinkPHP5.0 is split into multiple warehouses, mainly including:
Application project: Https://github.com/top-think/think
Core framework: Https://github.com/top-think/framework

The

is designed for application and core warehouse separation to support composer to update the core framework separately.
Clone the Download App project repository first
git clone https://github.com/top-think/think tp5
Then switch to the TP5 directory and clone the core framework repository:
git clone https ://github.com/top-think/framework thinkphp
Two repositories after cloning is complete, Just completed the ThinkPHP5.0 git mode download, if you need to update the core framework, only need to switch to the thinkphp core directory, and then execute:
git pull https://github.com/top-think/ The framework
if you are unfamiliar with the git command line, you can use any of the GIT clients to do so, which is no longer explained in detail.
No matter how you get the thinkphp framework, it's only a final step to verify that it's working.
Enter the address in the browser:
http://localhost/tp5/public/
If the browser output, then you have succeeded, if not, then check the relevant configuration or steps:

Canonical collation
ThinkPHP5 follows the PSR-2 naming convention and the PSR-4 Auto-load specification, and is aware of the following specifications:
directories and files
directories do not enforce specifications, hump and lowercase + underline modes are supported;
Class libraries, The function file is unified with. php suffix; The file name of the
class is defined in the namespace, and the path to the namespace is the same as the path to the class library file;
class file is named with the camel (first letter capitalized), the other file is named with lowercase + underscore, and the
class name and class file name are consistent. Uniform use of the Hump method named (capitalized); the name of the
function and class, property naming
Class takes the Hump method (capitalized), such as user, usertype, and does not need to add a suffix by default, for example Usercontroller should be named user directly;
The name of the function uses a lowercase letter and an underscore (beginning with a lowercase letter), such as GET_CLIENT_IP; the name of the
method uses the Hump method (the first letter lowercase), such as GetUserName; the name of the
property uses the Hump method (the first letter lowercase), for example TableName, instance;
a function or method that starts with a double underscore "__" as a magic method, such as __call and __autoload;
Constants and Configuration
constants are named with uppercase letters and underscores, such as App_path and THINK _path;
configuration parameters are named with lowercase letters and underscores, such as url_route_on and Url_convert;
data tables and fields
data tables and fields are named with lowercase underscores, and note that field names do not start with an underscore, such as Think_ The user table and the User_name field are not recommended for use with hump and Chinese as data table fields.
Apply Class Library namespace specification
apply the root namespace of the class library uniformly to the app (you can set app_namespace configuration parameter changes)
For example: App\index\controller\index and App\index\model\ User.
Structure Introduction
After you download the latest version of the framework, unzip to the web directory and see the initial directory structure as follows:

The deployment recommendation for 5.0 is that the public directory accesses content as a web directory, others are outside the web directory, and of course you have to modify the associated path in public/index.php. If this is not possible, remember to set access permissions for the directory or add protected files for the directory list.
router.php for PHP comes with webserver support for quick testing
Start command: Php-s localhost:8888 router.php
The 5.0 version comes with a complete application directory structure and the default application portal file, which developers can adjust flexibly.
The above directory structure and name can be changed, especially the directory structure of the application, depending on your portal file and configuration parameters.
Here is the directory structure i downloaded after the decompression

Simple configuration
Carefully, we can find that the entry file in the THINKPHP5 has changed relative to the THINKPHP3, In the ThinkPhp5 of the portal file is placed in the root directory of the public inside the index.php file, in fact, 5 relative to 3, the change is quite large, if the previous is the use of 3 written items. To upgrade to 5, the estimate is also a large project, need to be very careful to deal with.
We entered in front: http://localhost/tp5/public/
Viewing the contents of index.php in public can be seen in a somewhat similar context to the entry in THINKPHP3:
THINKPHP3 's entry file
Application Portal File

Detecting PHP environments
if (Version_compare (php_version, ' 5.3.0 ', ' < ') die (' Require PHP > 5.3.0! ');

Open Debug mode suggest the development phase to open the deployment phase comment or set to False
Define (' App_debug ', True);

Defining the App Catalog
Define (' App_name ', ' APP ');
Defining the App Catalog
Define (' App_path ', './app/');

Introducing the thinkphp entry file
Require './thinkphp/thinkphp.php ';

There's no code behind the pro ^_^, it's so simple.
THINKPHP5 's entry file
[Application Portal file]

Defining the App Catalog
Define (' App_path ', __dir__. ‘/.. /application/');
Loading the framework bootstrap file
Require __dir__. ‘/.. /thinkphp/start.php ';
So we will find that the portal file points to the application folder, and then go to the application folder, there is an index folder, there is a controller folder, open the index.php file, see:
<?php
namespace App\index\controller;

Class Index
{
Public Function Index ()
{
Return ' <style type= ' text/css ' >*{padding:0; margin:0 think_default_text{48px;} padding:4px: #2E5CD5 ; Cursor:pointer;text-decoration:none} a:hover{text-decoration:underline;} body{background: #fff; font-family: " Century Gothic "," Microsoft Yahei "; Color: #333; font-size:18px} h1{font-size:100px; font-weight:normal; margin-bottom:12px;} p{line-height:1.6em; font- size:42px}</style><div style= "padding:24px 48px;" > }
}
Where return returns the data, exactly what we entered earlier: http://localhost/tp5/public/%E6%89%80%E7%9C%8B%E5%88%B0%E5%AF%B9%E5%BA%94%E7%9A%84%E6% 95%b0%e6%8d%ae%e3%80%82
The following starts with a simple project file configuration (depending on your personal habits).
File creation
Start with the application folder first. Because we usually in a project will be divided between the front and back, so here in application to create some new files folder, as for the index folder can be used, or on his basis or directly as the previous folder.
Home folder
common.php file
config.php file
Controller folder
index.php file
View Folder
Index folder
index.html file
Model folder
Admin folder
common.php file
config.php file
Controller folder
index.php file
View Folder
Index folder
index.html file
Model folder
App_extend folder
common.php file
config.php file
Controller folder
Miaosha folder
Weixin folder
Tuangou folder
View Folder
Miaosha folder
Weixin folder
Tuangou folder
Model folder
Miaosha folder
Weixin folder
Tuangou folder
Common folder
An introduction to other configurations and related documents is skipped here. Believe that a little basic one should can read.
Simple data display
In the admin and Home Controller folder corresponding to the index.php file write the following code:
index.php implementation
<?php namespace App\home\controller; Use Think\controller; Class Index extends Controller {public Function Index () {return $this->fetch ();}}
The function of the display () method in Fetch () and THINKPHP3 is one should to realize the transmission of MV layer.
Fetch render Template Output
Display rendered content output
Assign template variable assignment
Engine init template engines
In the admin and Home View folder corresponding to the index.html file write the following code:
index.html implementation

<meta charset = "Utf-8" >

<body>

Welcome to icocos=name;;;;;;;;;;;

</body>

For view instantiation and related configuration, use and rendering see the official manual: View
Use: The browser to enter the following path, you can see the corresponding interface we want to see
Home
Http://127.0.0.1/ThComp3/public/home/index
Admin
Http://127.0.0.1/ThComp3/public/admin/index
This simply implements the processing between the M layer and the V layer in MVC.
Database configuration
First use Navicat or phpMyAdmin to create the corresponding database and table, and initialize some fields, and then insert a simple data, here I use Navicat (support most databases, simple operation).

Configuring Database-related properties
Configure the corresponding data information in the database.php of the root directory


Configuring Database-related properties

Configure the corresponding data information in the database.php of the root directory

<?php
// +----------------------------------------------------------------------
// | thinkphp [WE CAN do IT JUST THINK]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed (http://www.apache.org/licenses/LICENSE-2.0)
// +----------------------------------------------------------------------
// | author:liu21st <[email protected]>
// +----------------------------------------------------------------------

return [
Database type
' Type ' = ' mysql ',
Server address
' Hostname ' = ' 127.0.0.1 ',
Database name
' Database ' = ' Wwwicocos ',
User name
' Username ' = ' root ',
Password
' Password ' = ',
Port
' Hostport ' = ' 3306 ',
Connection DSN
' DSN ' = ',
Database connection Parameters
' Params ' = [],
Database encoding is UTF8 by default
' CharSet ' = ' utf8 ',
database table prefixes
' Prefix ' = ',
Database Debug mode
' Debug ' = True,
Database Deployment method: 0 Centralized (single server), 1 distributed (Master-slave server)
' Deploy ' = 0,
Whether the database reads and writes separate master-slave valid
' Rw_separate ' = False,
Number of master servers for read-write separation
' Master_num ' = 1,
Specify the number from the server
' Slave_no ' = ',
Whether the field is strictly checked for existence
' Fields_strict ' = true,
Data set return type array Arrays Collection collection objects
' Resultset_type ' = ' array ',
Whether to write timestamp fields automatically
' Auto_timestamp ' = False,
Whether SQL performance analysis is required
' Sql_explain ' = False,
];
You can also dynamically define connection information when you call the DB class
Db::connect ([
Database type
' Type ' = ' mysql ',
Database Connection DSN Configuration
' DSN ' = ',
Server address
' Hostname ' = ' 127.0.0.1 ',
Database name
' Database ' = ' thinkphp ',
Database user Name
' Username ' = ' root ',
Database Password
' Password ' = ',
Database connection Port
' Hostport ' = ',
Database connection Parameters
' Params ' = [],
Database encoding is UTF8 by default
' CharSet ' = ' utf8 ',
database table prefixes
' Prefix ' = ' think_ ',
]);
Or use a string method:
Db::connect (' Mysql://root:[email Protected]:3306/thinkphp#utf8 ');
Basic use
Once the database connection information is configured, we can run native SQL operations directly with the database, support query (query operations) and execute (write operations) methods, and support parameter binding.
Db::query (' select * from Think_user where id=? ', [8]); Db::execute (' INSERT into Think_user (ID, name) VALUES (?,?) ', [8, ' thinkphp ']);
Named placeholder bindings are also supported, for example:
Db::query (' select * from Think_user where Id=:id ', [' ID ' =>8]); Db::execute (' INSERT into Think_user (ID, name) VALUES (: ID,: Name) ', [' id ' =>8, ' name ' = ' thinkphp ']);
You can use multiple database connections, using
Db::connect ($config)->query (' select * from Think_user where Id=:id ', [' ID ' =>8]);
Config is a separate database configuration that supports arrays and strings, or it can be a configuration parameter name for a database connection.
Crud
Query: Basic Query
Query for one data using:
The table method must specify the full data table name
Db::table (' Think_user ')->where (' id ', 1)->find ();
Find method Query result does not exist, return null
Query data set using:
Db::table (' Think_user ')->where (' status ', 1)->select ();

The Select method query result does not exist and returns an empty array
If you set the data table prefix parameter, you can use the
Db::name (' user ')->where (' id ', 1)->find ();
Db::name (' user ')->where (' status ', 1)->select ();
Added: Adding a piece of data
To submit data to a database by using the Insert method of the Db class
$data = [' foo ' = ' bar ', ' bar ' = ' foo '];
Db::table (' Think_user ')->insert ($data);
If you configured the database prefix (prefix) in the database.php configuration file, you can submit the data directly using the name method of the Db class
Db::name (' user ')->insert ($data);
Insert method adds data successfully returns the number of added successes, insert normal returns 1
You can use the Getlastinsid method if you need to return the self-increment primary key for new data after adding data:
Db::name (' user ')->insert ($data);
$userId = db::name (' user ')->getlastinsid ();
Or add data directly using the Insertgetid method and return the primary key value:
Db::name (' user ')->insertgetid ($data);
Insertgetid method Add data successfully returns the self-increment primary key for adding data
Update: Updating data in a data table
Db::table (' Think_user ')->where (' id ', 1)->update ([' name ' = ' thinkphp ']);
If the data contains a primary key, you can use it directly:
Db::table (' Think_user ')
->update ([' name ' = ' thinkphp ', ' ID ' =>1]);
The Update method returns the number of bars that affect the data, without modifying any data to return 0
If the data you want to update needs to use SQL functions or other fields, you can use the following method:
Db::table (' Think_user ')->where (' id ', 1)->update ([
' Login_time ' = [' exp ', ' Now () '],
' Login_times ' = [' exp ', ' login_times+1 '],
]);
Update the value of a field:
Db::table (' Think_user ')->where (' id ', 1)->setfield (' name ', ' thinkphp ');
The SetField method returns the number of bars that affect the data, without modifying any data fields returned 0
Delete: Delete data from a data table
Delete based on primary key
Db::table (' Think_user ')->delete (1);
Db::table (' Think_user ')->delete ([+]);

Conditional delete
Db::table (' Think_user ')->where (' id ', 1)->delete ();
Db::table (' Think_user ')->where (' id ', ' < ', ten)->delete ();
The Delete method returns the number of bars that affect the data, and no delete returns 0
Helper functions
Delete based on primary key
db (' user ')->delete (1);
Conditional delete
db (' user ')->where (' id ', 1)->delete ();
Query: Conditional Query method
Where method
You can use the Where method to query for and conditions:
Db::table (' Think_user ')->where (' name ', ' like ', '%thinkphp ')->where (' status ', 1)->find ();
and queries with the same criteria for multiple fields can be simplified to the following ways:
Db::table (' Think_user ')->where (' Name&title ', ' like ', '%thinkphp ')->find ();
Whereor method
Use the Whereor method for or query:
Db::table (' Think_user ')->where (' name ', ' like ', '%thinkphp ')->whereor (' title ', ' Like ', '%thinkphp ')->find ( );
An or query with the same criteria for multiple fields can be simplified to the following ways:
Db::table (' Think_user ')->where (' Name|title ', ' like ', '%thinkphp ')->find ();
Other advanced Operations Reference official manual: Database operations
Model Introduction
Model class definition
If the connection attribute is defined within a model class, the model will automatically connect to the given database connection instead of the default connection information set in the configuration file, usually for some data tables other than the current database connection, for example:
Setting database connection information separately in the model
namespace App\index\model;

Use Think\model;

Class User extends Model {
protected $connection = [
Database type
' Type ' = ' mysql ',
Database Connection DSN Configuration
' DSN ' = ',
Server address
' Hostname ' = ' 127.0.0.1 ',
Database name
' Database ' = ' thinkphp ',
Database user Name
' Username ' = ' root ',
Database Password
' Password ' = ',
Database connection Port
' Hostport ' = ',
Database connection Parameters
' Params ' = [],
Database encoding is UTF8 by default
' CharSet ' = ' utf8 ',
database table prefixes
' Prefix ' = ' think_ ',
];
}
You can also define a DSN string, for example:
Setting database connection information separately in the model
namespace App\index\model;

Use Think\model;

Class User extends Model
{
or use a string definition
protected $connection = ' Mysql://root:[email Protected]:3306/thinkphp#utf8 ';
}
As with the parameters that connect to the database, the value of the connection property can also be set to the database's configuration parameters.
5.0 data table prefixes for the current model are not supported separately.
Model calls
Model classes can use either static or instantiation calls, such as:
Static call
$user = User::get (1);
$user->name = ' thinkphp ';
$user->save ();

Instantiating a model
$user = new User;
$user->name= ' thinkphp ';
$user->save ();

Using the Loader class instantiation (Singleton)
$user = Loader::model (' user ');

Or use the helper function ' model '
$user = Model (' user ');
$user->name= ' thinkphp ';
$user->save ();
Model initialization
The model also supports initialization, unlike the initialization of the controller, which is the initialize of the model, as follows
namespace App\index\model;

Use Think\model;

Class Index extends Model
{

Custom initialization
protected function Initialize ()
{
Need to call ' Model ' of ' Initialize ' method
Parent::initialize ();
TODO: Custom Initialization
}
}
It is also possible to use the static Init method, and it is important to note that Init executes only when the first instantiation is performed, and the method needs to be aware of the specification of the static invocation, as follows:
namespace App\index\model;

Use Think\model;

Class Index extends Model
{

Custom initialization
protected static function init ()
{
TODO: Custom Initialization
}
}
Crud
Increase
Add a piece of data
The first is to instantiate the model object and then assign and save:
$user = new User;
$user->name = ' thinkphp ';
$user->email = ' [email protected] ';
$user->save ();
You can also use the data method to assign values in bulk:
$user = new User;
$user->data ([
' Name ' = ' thinkphp ',
' Email ' = ' [email protected] '
]);
$user->save ();
or pass in data directly at the time of instantiation
$user = New User ([
' Name ' = ' thinkphp ',
' Email ' = ' [email protected] '
]);
$user->save ();
If you need to filter data for non-data table fields, you can use:
$user = new User ($_post);
Filter Non-Data table field data in the post array
$user->allowfield (True)->save ();
If you assign a value to the model through an external commit, and you want to specify some field writes, you can use:
$user = new User ($_post);
Only the name and email fields in the post array will be written to
$user->allowfield ([' Name ', ' email '])->save ();

The new data returned by the Save method is the number of records written.
Update
Find and update
After the data is removed, the data is updated after the field contents are changed.
$user = User::get (1);
$user->name = ' thinkphp ';
$user->email = ' [email protected] ';
$user->save ();
Update data directly
You can also update data directly with update criteria
$user = new User;
Save method The second parameter is the update condition
$user->save ([
' Name ' = ' thinkphp ',
' Email ' = ' [email protected] '
],[' id ' = 1]);
The above two ways to update the data, if you need to filter the data of non-table fields, you can use:
$user = new User ();
Filter Non-Data table field data in the post array
$user->allowfield (True)->save ($_post,[' id ' = 1]);
If you assign a value to the model through an external commit, and you want to specify some field writes, you can use:
$user = new User (); "([' name ', ' email '])->save ($_post, [' id ' = 1]);
Delete
Delete current model
Deleting model data allows you to invoke the Delete method after instantiation.
$user = User::get (1);
$user->delete ();
Delete based on primary key
or call a static method directly
User::d Estroy (1);
Supports bulk deletion of multiple data
User::d (' Estroy ');
Or
User::d Estroy ([+]);
Conditional delete
Use an array for conditional deletion, for example:
Delete data with a status of 0
User::d Estroy ([' status ' = 0]);
The use of closures is also supported, for example:
User::d Estroy (function ($query) {
$query->where (' id ', ' > ', 10);
});
or delete through the query criteria of the database class
User::where (' id ', ' > ', Ten)->delete ();
Inquire
Get a single data
Ways to get a single data include:
Remove data with primary key 1
$user = User::get (1);
Echo $user->name;

Using array queries
$user = User::get ([' name ' = ' thinkphp ']);

Using a closed packet query
$user = User::get (function ($query) {
$query->where (' name ', ' thinkphp ');
});
Echo $user->name;
or call the query method after instantiating the model
$user = new User ();
Querying individual data
$user->where (' name ', ' thinkphp ')
->find ();
The Get or Find method returns an object instance of the current model, which you can use to model the method.
Other advanced Operations Reference official manuals: Model operations
Introductory summary
ThinkPHP5. With ThinkPHP3. Differences in usage between
Because the study TP5 time is not very long, the following differences are listed in the first place:
1, the past single-letter function has been completely replaced, as follows:
S=>cache,c=>config,m/d=>model,u=>url,i=>input,e=>exception,l=>lang,a=>controller,r= >action
2, template rendering: $this->display () = return view ()/return $this->fetch ();
3. Call itself model in model: $this = db::table ($this->table)
4. Naming when creating a new controller and model:
① controller remove suffix Controller:usercontroller = User

② model minus suffix Model:usermodel = User
5. URL Access:
If the controller name uses the Hump method, access requires an underscore link between the letters.

Eg: Controller named AddUser, Access is accessed using Add_user
6, in TP5 support configuration level two parameters (that is, two-dimensional array), configuration file, two-level configuration parameters read:
①config::get (' User.type ');

②config (' User.type ');
7. The operation of the ternary operator is supported in the template: {$info. status? $info. msg: $info. Error} also supports this notation:
{$varname. aa?? ' xxx '} or {$varname. aa?: ' xxx '}
8. TP5 built-in tag:
System built-in tags, volist, switch, if, ElseIf, else, foreach, compare (including all comparison labels), (not) present, (not) empty, (not) defined, etc.
9, TP5 Data validation:
$validate = new Validate ([' name ' = ' require|max:25 ', ' email ' = ' email ']);

$data = [' name ' = ' thinkphp ', ' email ' = ' [email protected] '];

if (!validate->check ($data)) {

Debug::d UMP ($validate->geterror ());

}
Note: Use the helper function to instantiate the validator-$validate = Validate (' User ');
10, TP5 realized the built-in paging, using the following:
Query for user data with a status of 1 and 10 data per page
$list = Model (' User ')->where (' status ', 1)->paginate (10);

$page = $this->render ();

$this->assign (' _list ', $list);

$this->assign (' _page ', $page);

return $this->fetch ();
The paging output code in the template file is as follows:
<div>{$_page}</div>

The end of the thinkphp 5.* far more than that.

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.