Introduction:
1.1 PHP is suitable for rapid development of web interfaces. Its simplicity of syntax and speed of development have attracted many users, and it once occupied the top 5 programming languages. With the rapid development, many excellent frameworks have emerged, the more famous ones are ThinkPHP, Laravel, and Yii.
1.2 Framework selection
- ThinkPHP is easy to use, rich in domestic development documents, and active in the community; but the directory structure is not neat, it is not difficult to go deep, and it is suitable for small and medium-sized projects.
- Laravel has a clear structure, complete functions, rich tools, and a strong community, but it is difficult to get started; there are many files and relatively bloated. Suitable for medium to large projects.
- Yii OOP design concept, easy to use, fast development speed, powerful performance, and rich functions; most of the documents are in English, the learning cost is high, and the technical requirements are high. Suitable for medium to large projects.
Two, ThinkPHP5.0 directory
2.1 Thinkphp5.0 is relatively mature and stable, official address: https://www.thinkphp.cn/down/framework.html
If the above address does not work, use the automatic download address: https://www.thinkphp.cn/donate/download/id/870.html
2.2 Follow the directory description
project 应用部署目录
├─composer.json composer定义文件
├─README.md README文件
├─build.php 自动生成定义文件(参考)
├─LICENSE.txt 授权说明文件
├─application 应用目录(可设置)
│ ├─common 公共模块目录(可更改)
│ ├─runtime 应用的运行时目录(可写,可设置)
│ ├─module 模块目录
│ │ ├─config.php 模块配置文件
│ │ ├─common.php 模块函数文件
│ │ ├─controller 控制器目录
│ │ ├─model 模型目录
│ │ ├─view 视图目录
│ │ ├─ ... 更多类库目录
│ ├─common.php 公共函数文件
│ ├─route.php 路由配置文件
│ ├─database.php 数据库配置文件
│ └─config.php 公共配置文件
├─public WEB部署目录(对外访问目录)
│ ├─index.php 应用入口文件
│ ├─.htaccess 用于apache的重写
│ └─router.php 快速测试文件(用于自带webserver)
├─thinkphp 框架系统目录
│ ├─library 框架类库目录
│ │ ├─behavior 行为类库目录
│ │ ├─think Think类库包目录
│ │ ├─org Org类库包目录
│ │ ├─traits 系统Traits目录
│ │ ├─ ... 更多类库目录
│ ├─extend 扩展类库目录(可自定义)
│ ├─vendor 第三方类库目录
│ ├─mode 应用模式目录
│ ├─tpl 系统模板目录
│ ├─base.php 基础文件
│ ├─convention.php 框架惯例配置文件
│ └─start.php 框架引导文件
2.3 Put the downloaded thinkphp in the root directory of the website to access, and enter http://localhost/tp5/public/ in the browser
2.3 Access path
Default path: http://localhost/tp5/public/
Full path: http://localhost/tp5/public/index.php/index/index/index
The above looks like a lot of indexes, which are quite messy. We can write another controller to understand clearly
http://localhost/tp5/public/index.php/amodule/bcontroller/caction/id/1
[Request protocol http]+[domain name]+[tp directory]+[web entry public]+[entry file]+[module name]+[controller]+[operation]+[parameter]+[parameter name]+[ parameter]+[parameter name]...
2.4 Simplify the access path and batch registration
Original path: http://localhost/tp5/public/index.php/amodule/bcontroller/caction/id/1
The first step, remove the public
Move the index.php in the public to the root directory, modify the corresponding application directory and boot file
Original file: /../ means to fall back to the upper-level directory, where the upper-level directory of index.php is tp and the directory
<?php
// [ 应用入口文件 ]
// 定义应用目录
define('APP_PATH', __DIR__ . '/../application/');
// 加载框架引导文件
require __DIR__ . '/../thinkphp/start.php';
The modified file, __DIR__ indicates the location of the current file, here is the directory where index.php is located
<?php
// [ 应用入口文件 ]
// 定义应用目录
define('APP_PATH', __DIR__ . '/application/');
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';
The second step is to configure httpd.conf, search all AllowOverride none to AllowOverride ALL
<Directory "D:/server/apache/cgi-bin">
AllowOverride none 改为 AllowOverride ALL
Options None
Order allow,deny
Allow from all
</Directory>
The third step is to configure .htaccess
Create a .htaccess file in the root directory, if it exists elsewhere, you can copy it
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?s=$1 [QSA,PT,L]
</IfModule>
The access path at this point is like this http://localhost/tp5/amodule/bcontroller/caction
The fourth step is to use routing to remove modules and controllers
Add routing in tp5 -> application -> route.php
<?php
return [
'__pattern__' => [
'name' => '\w+',
],
'[hello]' => [
':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
':name' => ['index/hello', ['method' => 'post']],
],
'[test]' => [
'new' => ['amodule/bcontroller/caction', ['method' => 'get']],
],
];
In this way, the access path will be shortened to http://localhost/tp5/test/new
or modify like this
<?php
return [
'__pattern__' => [
'name' => '\w+',
],
'[hello]' => [
':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
':name' => ['index/hello', ['method' => 'post']],
],
'new/[:name]' => 'amodule/bcontroller/caction',
];
The access path will become http://localhost/tp5/new
2.5 The second simplified route method Route::rule
Static route:
<?php
// return [
// '__pattern__' => [
// 'name' => '\w+',
// ],
// '[hello]' => [
// ':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
// ':name' => ['index/hello', ['method' => 'post']],
// ],
// // '[test]' => [
// // 'new' => ['amodule/bcontroller/caction', ['method' => 'get']],
// // ],
// // 'new/[:name]' => 'amodule/bcontroller/caction',
// ];
//引用路由模块
use think\Route;
//注册路由到amodule模块的bcontroller控制器的caction操作
//静态路由
Route::rule('new', 'amodule/bcontroller/caction','GET');
The access path will become http://localhost/tp5/new
Notice:
The part of dynamic registration route must be removed
Must add reference use think\Route;
Dynamic routing:
<?php
// return [
// '__pattern__' => [
// 'name' => '\w+',
// ],
// '[hello]' => [
// ':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
// ':name' => ['index/hello', ['method' => 'post']],
// ],
// // '[test]' => [
// // 'new' => ['amodule/bcontroller/caction', ['method' => 'get']],
// // ],
// // 'new/[:name]' => 'amodule/bcontroller/caction',
// ];
//引用路由模块
use think\Route;
//注册路由到amodule模块的bcontroller控制器的caction操作
//静态路由册
Route::rule('new', 'amodule/bcontroller/caction','GET');
//动态路由册
Route::rule('test/:id','amodule/bcontroller/daction','GET');
The access path will become http://localhost/tp5/new http://localhost/tp5/test/1
Or directly specify the GET type without referencing think\Route
<?php
// return [
// '__pattern__' => [
// 'name' => '\w+',
// ],
// '[hello]' => [
// ':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
// ':name' => ['index/hello', ['method' => 'post']],
// ],
// // '[test]' => [
// // 'new' => ['amodule/bcontroller/caction', ['method' => 'get']],
// // ],
// // 'new/[:name]' => 'amodule/bcontroller/caction',
// ];
//引用路由模块
// use think\Route;
// //注册路由到amodule模块的bcontroller控制器的caction操作
// //静态路由册
// Route::rule('new', 'amodule/bcontroller/caction','GET');
// //动态路由册
// Route::rule('test/:id','amodule/bcontroller/daction','GET');
\think\Route::get('new','amodule/bcontroller/caction');
\think\Route::get('test/:id','amodule/bcontroller/daction');
The access path will become http://localhost/tp5/new http://localhost/tp5/test/1
2.5 The third simplified path method, binding Route::bind
// //绑定到模块/控制器/操作
// 绑定当前的URL到 amodule模块
Route::bind('amodule');
// 绑定当前的URL到 amodule模块的bcontroller控制器
Route::bind('amodule/bcontroller');
The access path will become http://localhost/tp5/caction
Of course, other directories can also be bound, such as controllers, namespaces, classes, etc.
Three ThinkPHP5.0 configuration
3.1 Entry file
3.2 Application configuration
3.3 Database configuration
3.4 Access domain name configuration
Four, system architecture
4.1 The typical URL access rules of ThinkPHP5.0 without routing enabled are:
4.2 Support switching to command line access, if switching to command line mode, the following access rules are:
>php.exe index.php (application entry file) module/controller/operation/[parameter name/parameter value...]
4.3 Whether it is URL access or command line access, the access address in PATHINFO mode is used, and the separator of PATHINFO can be set.
4.4 thinkphp5 cancels the concept of URL mode, URL access in normal mode is no longer supported, if the server does not support PATHINFO, you can use compatibility mode to access as follows:
4.5 Simplify URL access and hide application entry files
1. The mod_rewrite.so module is loaded in the httpd.conf configuration file
2. AllowOverride None Change None to All
3. Save the following content as.htaccess
a file and put it in the same directory as the application entry file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
4.6 Hidden modules
Since multi-module support is adopted by default, in the case of multiple modules, the current module must be identified in the URL address. If there is only one module, module binding can be performed by adding the following code to the public file of the application:
// 绑定index模块
\think\Route::bind('module','index');
After setting, our URL access address becomes:
http://serverName/application entry/controller/operation/[parameter name/parameter value...] // The accessed module is the index module
4.7 Hide Controller
If your application is relatively simple and there is only one module and controller, you can bind the module and controller in the application common file, as follows:
// 绑定index模块的index控制器
\think\Route::bind('module','index/index');
After setting, our URL access address becomes:
http://serverName/application entry/operation/[parameter name/parameter value...] // The accessed module is the index module, and the controller is the Index controller
five routes
5.1 The default URL rules adopted by ThinkPHP5.0 are:
5.2 Normal mode, turn off routing, completely use the default pathinfo URL:
'url_route_on' => false
After the routing is closed, no routing rules will be parsed, and the default PATH_INFO mode is used to access the URL:
module/controller/action/param/value/...
5.3 Hybrid mode, enable routing, and use routing + default PATH_INFO:
'url_route_on' => true
5.4 Register routing, dynamic registration
Use the register method of the Route class to register routing rules (usually you can register in the public file of the application, or register in batches in the public file after defining the configuration file), for example, after registering the following routing rules:
\think\Route::register('new/:id','index/New/read');
We visit:
http://serverName/new/5
The routing rule definition of ThinkPHP5.0 starts from the root directory, not based on the module name.
In fact, it is accessed:
http://serverName/index/new/read/id/5
Six, the controller
6.1 ThinkPHP introduces the concept of hierarchical controllers. The controller accessed through the URL is the access controller layer (Controller) or the main controller. The access controller is \think\App
called and instantiated by the class without manual instantiation.
6.2 After URL parsing and routing, the current URL address will be parsed to [module/controller/operation], which is actually to execute a certain operation method of a certain controller class. The following is an example:
namespace app\index\controller;
class New
{
public function index(){
return 'index';
}
public function add(){
return 'add';
}
public function edit($id){
return 'edit:'.$id;
}
}
6.3 The currently defined main controller is located under the index module, so when accessing pages with different URL addresses, the output is as follows:
http://serverName/index/new/index // 输出 index
http://serverName/index/new/add // 输出 add
http://serverName/index/new/edit/id/5 // 输出 edit:5
seven view
7.1 The view function is completed by the Think\View class and the template engine (driver) class together
Instantiate the view class
// 实例化视图类
$view = new \think\View();
// 渲染模板输出
return $view->fetch();
7.2 If your controller inherits the \think\Controller class, you can use it directly
// 渲染模板输出
return $this->fetch();
It should be noted that the view fetch method of ThinkPHP5 does not directly render the output, but only returns the parsed content. If the view analysis content is returned in the controller class, the rendering output system will automatically call the send method of the think\Response class for rendering output.
Eight, the database
8.1 Global configuration definition
The common configuration method is to add the following configuration parameters in the public configuration file or module configuration file:
'database'=> [
// 数据库类型
'type' => 'mysql',
// 数据库连接DSN配置
'dsn' => '',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'thinkphp',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '',
// 数据库连接端口
'hostport' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'think_',
// 数据库调试模式
'debug' => true,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
];
8.2 also supports the definition of independent database configuration files. For example, it is defined in the application/database.php file as follows:
return [
// 数据库类型
'type' => 'mysql',
// 数据库连接DSN配置
'dsn' => '',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'thinkphp',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '',
// 数据库连接端口
'hostport' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'think_',
// 数据库调试模式
'debug' => false,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
];
8.3 can also support simplified DSN database connection string writing (support most connection parameters), for example:
'database'=> 'mysql://root:[email protected]:3306/thinkphp#utf8'
If necessary, you can define different database connection information for each module, just add the database setting parameter in the module configuration file.
8.4 Connection parameters
You can add database connection parameters for different connection needs, for example:
If you need to use a long connection, you can define it in the following way:
'params' => [PDO::ATTR_PERSISTENT => true],
Nine input, variable acquisition
9.1 Get GET variables
\think\Input::get('id'); // 获取某个get变量
\think\Input::get('name'); // 获取get变量
\think\Input::get(); // 获取所有的get变量(数组)
Or use the built-in shortcut I method to achieve the same functionality:
9.2 Get POST variables
\think\Input::post('name'); // 获取某个post变量
\think\Input::post(); // 获取全部的post变量
Use the shortcut method to achieve:
I('post.name');
I('post.');
9.3 Get PUT variables
\think\Input::put('name'); // 获取某个put变量
\think\Input::put(); // 获取全部的put变量
Use the shortcut method to achieve:
I('put.name');
I('put.');
9.4 Get PARAM variable
PARAM variable is a variable acquisition method provided by the framework to automatically identify GET, POST or PUT requests, for example:
\think\Input::param('name');
如果当前是get请求,那么等效于
\think\Input::get('name');
如果当前是post请求,则等同于
\think\Input::post('name');
Use the shortcut method to achieve:
I('param.name');
I('param.');
或者
I('name');
I('');
Because the I function uses the PARAM variable reading method by default.
9.5 Get the REQUEST variable
\think\Input::request('id'); // 获取某个request变量
\think\Input::request(); // 获取全部的request变量
Use the shortcut method to achieve:
9.6 Get the SERVER variable
\think\Input::server('PHP_SELF'); // 获取某个server变量
\think\Input::server(); // 获取全部的server变量
Use the shortcut method to achieve:
I('server.PHP_SELF');
I('server.');
9.7 Get SESSION variables
\think\Input::session('user_id'); // 获取某个session变量
\think\Input::session(); // 获取全部的session变量
Use the shortcut method to achieve:
I('session.user_id');
I('session.');
9.8 Get Cookie variable
\think\Input::cookie('user_id'); // 获取某个cookie变量
\think\Input::cookie(); // 获取全部的cookie变量
Use the shortcut method to achieve:
I('cookie.user_id');
I('cookie.');
9.9 Variable filtering
Supports filtering of acquired variables, including function, method filtering, and PHP's built-in Types of filters, for example:
\think\Input::get('name','htmlspecialchars'); // 获取get变量 并用htmlspecialchars函数过滤
\think\Input::param('username','strip_tags'); // 获取param变量 并用strip_tags函数过滤
\think\Input::post('name','org\Filter::safeHtml'); // 获取post变量 并用org\Filter类的safeHtml方法过滤
Multiple filtering rules can be passed in, for example:
\think\Input::param('username','strip_tags,strtolower'); // 获取param变量 并依次调用strip_tags、strtolower函数过滤
The Input class also supports Filter ID filtering provided by PHP, for example:
\think\Input::post('email',FILTER_VALIDATE_EMAIL);
The framework provides conversion support for FilterID, so you can also use strings, for example:
\think\Input::post('email','email');
When the FilterID is defined in the form of a string, the system will automatically perform a filter_id call and convert it into a Filter constant.
The specific string is defined according to the return value of the filter_list function.
It should be noted that if Filter ID is used for filtering, false will be returned if the filtering requirements are not met, so you need to cooperate with the default value to ensure that the final value meets your specifications.
For example,
\think\Input::post('email',FILTER_VALIDATE_EMAIL,'');
It means that if it is not a standard email address, return an empty string.
9.10 Variable Modifiers
The I function supports the use of modifiers for variables, which can better filter variables.
The usage is as follows:
I('variable type. variable name/modifier');
or
\think\Input::get('variable name/modifier');
For example:
I('get.id/d');
I('post.name/s');
I('post.ids/a');
\think\Input::get('id/d');
The default variable modifiers of ThinkPHP5.0 are /s
, if you need to pass in variables other than strings, you can use the following modifiers, including:
Modifier | effect |
---|---|
s | cast to string type |
d | coercion to integer type |
b | coerce to boolean type |
a | cast to array type |
f | coerce to float type |
If the data you want to get is an array, please pay attention to adding
/a
modifiers to get it correctly.