ThinkPHP Outline

1 Introduction

1.1 What is ThinkPHP

  • What is ThinkPHP

ThinkPHP is an open source PHP development framework, which follows the MVC (Model-View-Controller) design pattern, and has the characteristics of high efficiency, flexibility, security, and simplicity. ThinkPHP provides a wealth of functions and tools, including database operations, caching, validation, template engines, etc., which can help developers quickly build high-quality web applications. At the same time, ThinkPHP also has comprehensive documentation and community support, making it an excellent choice for PHP developers.

1.2 History of ThinkPHP

  • History of ThinkPHP: ThinkPHP is an open source PHP development framework created and maintained by Chinese developers. Its first version was released in 2006. After years of development and iteration, it has become one of the most popular PHP frameworks in China. ThinkPHP adopts the MVC design pattern, which has the characteristics of high efficiency, simplicity, security, and scalability, and is widely used in the development of various Web applications.

1.3 Advantages of ThinkPHP - simple and efficient routing function

  • Powerful template engine
  • Rich database support
  • High security authentication and authorization mechanism
  • Rich third-party library support
  • Flexible plug-in mechanism
  • Perfect error handling and debugging mechanism
  • Detailed development documentation and community support

2. Installation and configuration

2.1 Environmental requirements

  • Environmental requirements:
    • PHP >= 5.6.0
    • PDO PHP Extension
    • MBstring PHP Extension
    • CURL PHP Extension
    • OpenSSL PHP Extension

2.2 Install ThinkPHP

  • Install ThinkPHP
    • Method 1: Install using Composer

composer create-project topthink/think tp5

    • Method 2: Manual installation
      1. Download the latest version of the ThinkPHP framework
      2. Unzip into the project directory
      3. Configure a virtual host or use PHP's built-in server to start
    • Method 3: Install using Git

git clone https://github.com/top-think/think.git

2.3 Configure ThinkPHP- Configure database connection information, URL mode, default access block

'DB_TYPE' => 'mysql', // database type
'DB_HOST' => 'localhost', // server address
'DB_NAME' => 'test', // database name
'DB_USER' => 'root', // username
'DB_PWD' => '', // password
'DB_PORT' => '3306', // port
'DB_PREFIX' => 'think_', // database table prefix

'URL_MODEL' => 2, // URL mode

'DEFAULT_MODULE' => 'Home', // default module

3. MVC pattern

3.1 What is the MVC pattern

  • The MVC pattern is a software architecture pattern that divides an application into three core parts: model (Model), view (View) and controller (Controller).
  • Model (Model): Responsible for processing the data logic of the application, including operations such as data storage, retrieval, update, and deletion.
  • View (View): Responsible for displaying data to users, usually generating pages through technologies such as HTML, CSS, and JavaScript.
  • Controller (Controller): responsible for processing the user's request and calling the corresponding model and view, combining them into a complete response and returning it to the user.
  • The MVC pattern can separate various parts of the application for easy development, testing and maintenance.

3.2 MVC pattern in ThinkPHP

  • In ThinkPHP, the MVC pattern is divided into three parts: model, view, and controller.
  • Model (Model): Responsible for data processing, including operations such as addition, deletion, modification, and query of data.
  • View (View): Responsible for the display of data, presenting the processed data to the user in the form of a page.
  • Controller: Responsible for receiving user requests, calling corresponding models and views, and finally returning processed data to users.
  • Through the separation of MVC mode, the code can be made clearer and easier to maintain. At the same time, it can also enable different developers to develop in different modules, improving development efficiency.
  • In ThinkPHP, the steps to develop using the MVC pattern are as follows:
    1. Define the model: Create a model directory under the /application directory, and then create a corresponding model file under this directory.
    2. Define a view: Create a view directory under the /application directory, and then create a corresponding view file under this directory.
    3. Define the controller: Create a controller directory under the /application directory, and then create a corresponding controller file under this directory.
    4. Call the model and view in the controller to handle the user's request.

3.3 Advantages of the MVC pattern - Reduced coupling: The MVC pattern divides the application into three parts so that they can be developed, tested, maintained and modified independently, thus reducing the coupling between them.

  • Improve reusability: The MVC pattern enables models and views to be reused in different applications, thereby improving code reusability.
  • Easy to maintain: The MVC pattern divides the application into three parts, so that each part can be modified and maintained independently, making the entire application easier to maintain.
  • Better scalability: The MVC pattern makes it easier to extend the application, such as adding new views or controllers, without affecting other parts of the code.
  • Better testability: The MVC pattern enables each part of the application to be tested independently, thereby improving the efficiency and reliability of the test.

4. Routing

4.1 What is routing

  • Routing refers to the process of mapping URL requests to specific handlers.
  • In ThinkPHP, the routing configuration file is located in the route.php file in the route directory under the project root directory.
  • Routing configuration can be defined in various ways such as closure functions, controller methods, and static methods.
  • For example, we can define the following routing rules in the route.php file:
use think\facade\Route;

// Closure function routing
Route::get('hello/:name', function ($name) {
    return 'Hello,' . $name . '!';
});

//Controller method routing
Route::get('user/:id', 'index/User/read');

// static method routing
Route::get('test', '\app\index\controller\Test::index');
  • In the above code, three different types of routing rules are defined, namely, closure function routing, controller method routing, and static method routing.
  • Closure function routing handles requests through anonymous functions, controller method routing handles requests by specifying the controller class and method, and static method routing handles requests by specifying the class where the static method resides.
  • Through routing configuration, we can map URL requests to specific handlers to achieve more flexible and convenient URL management.

4.2 Routing in ThinkPHP

  • Routing in ThinkPHP
    • basic routingRoute::rule('hello/:name', 'index/hello');
    • routing parametersRoute::rule('blog/:id', 'blog/read');
    • routing packet
Route::group('admin', function () {
  Route::rule('user', 'admin/user/index');     
  Route::rule('login', 'admin/login/index'); 
}); 
    • route aliasRoute::rule('user/:id', 'index/user/read')->alias('user');
    • route redirectionRoute::rule('home', 'index/index/index', 'redirect');
    • routing cache'url_route_cache' => true,

4.3 Advantages of routing - parameters in the URL can be hidden, increasing the beauty and security of the URL.

  • URLs can be bound to specific controllers and methods for easy management and maintenance.
  • URL redirection and customization can be performed through routing rules, which improves flexibility and scalability.
  • Different routing rules can be matched according to different request methods and parameters to achieve finer-grained control and processing.
  • The routing rules of different modules can be separated and managed through routing grouping, which improves the readability and maintainability of the code.

5. Controller

5.1 What is a controller

  • What is a controller:
    The controller is the C in the MVC pattern, and it is the control center of the entire application. It is responsible for receiving user requests, calling models and views to complete user needs. The controller can call different models and views to achieve different functions according to different requests. Here is a simple controller example:
<?php 
  namespace app\index\controller; 
  class Index {
    public function index()     {
      return 'Hello, ThinkPHP!';     
    } 
  }

This controller is defined in the app\index\controller\Index.php file with the namespace app\index\controller. There is an index method in the controller. When the user requests access to /index/index, this method is called and returns Hello, ThinkPHP!.

5.2 Controllers in ThinkPHP

  • The controller is C in the MVC architecture, which is mainly responsible for processing user requests and returning response results.
  • The controller naming convention in ThinkPHP is: module name + Controller, such as IndexController.
  • The method in the controller is the operation requested by the user and can be accessed through the URL.
  • Controllers can use the $this->assign() method to pass variables to templates.
  • Controllers can use the $this->redirect() method for redirection.
  • In the controller, you can use the $this->error() method and $this->success() method to return error and success information respectively.
  • Controllers in ThinkPHP can inherit the Think\Controller class, or inherit a custom base class.
  • Controllers can use the __construct() method for initialization.
  • The _before() method and _after() method can be used in the controller to perform pre- and post-operations.
  • The _ajax() method and _json() method can be used in the controller to return Ajax request and JSON data respectively.
  • The _table() method and _export() method can be used in the controller to output the table and export data respectively.

5.3 Advantages of the controller - the code can be modularized through the controller, making the code clearer and easier to understand.

  • The controller can process and respond to requests and implement business logic.
  • The controller can call the method of the model layer to realize the operation on the data.
  • The controller can perform authority control to protect the security of the system.
  • The controller can realize routing control, which is convenient for URL design and management.

6. Model

6.1 What is a model

  • The model is M in the MVC architecture, that is, the data model, which is used to process data addition, deletion, modification and query operations.
  • Models usually correspond to tables in the database, and a model class corresponds to a table.
  • Models can define data validation rules, association relationships, operate databases, etc.
  • The definition of the model is generally placed in the application\index\model directory, and the model can be defined by inheriting the think\Model class.
  • Sample code:
namespace app\index\model;

use think\Model;

class User extends Model
{
    // Define the data table name
    protected $table = 'user';

    // define primary key
    protected $pk = 'id';

    // define the timestamp field
    protected $autoWriteTimestamp = true;

    // define data validation rules
    protected $rule = [
        'name|name' => 'require|max:20',
        'age|age' => 'require|integer|between:1,120',
        'email|mailbox' => 'email|unique:user',
    ];

    // define the relationship
    public function orders()
    {
        return $this->hasMany('Order', 'user_id', 'id');
    }

    // Define the operation database
    public function getUserById($id)
    {
        return $this->where('id', $id)->find();
    }
}

6.2 Models in ThinkPHP

  • model definition

The model in ThinkPHP uses the MVC design pattern, and the model is mainly responsible for dealing with the database, processing data additions, deletions, modifications, and other operations. In ThinkPHP, a model corresponds to a database table, and the table can be operated through the model.

  • use of models
  1. define model

To define a model, you need to inherit the Think\Model class, for example, to define a User model:

namespace app\index\model;

use think\Model;

class User extends Model
{
    // The data table associated with the model
    protected $table = 'user';

    // model's primary key
    protected $pk = 'id';

    // Field information of the model
    protected $schema = [
        'id'         => 'int',
        'username'   => 'string',
        'password'   => 'string',
        'create_time'=> 'int',
        'update_time'=> 'int',
    ];
}

2. Increase data

$user = new User;
$user->username = 'admin';
$user->password = md5('123456');
$user->create_time = time();
$user->save();

3. Query data

// query all data
$users = User::select();

// Query a single piece of data based on the primary key
$user = User::get(1);

// query the data of the specified field
$users = User::field('id,username')->select();

// Query conditions
$users = User::where('username', 'admin')->select();

// Paging query
$users = User::paginate(10);

4. Update data

$user = User::get(1);
$user->username = 'admin2';
$user->save();

5. Delete data

$user = User::get(1);
$user->delete();
  • model association

Models in ThinkPHP support a variety of association methods, including one-to-one, one-to-many, many-to-many and other association methods. For example, define a User model and an Order model, a user can correspond to multiple orders, and an order can only correspond to one user:

namespace app\index\model;

use think\Model;

class User extends Model
{
    // define a one-to-many relationship
    public function orders()
    {
        return $this->hasMany('Order');
    }
}

class Order extends Model
{
    // define a one-to-one relationship
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Query users and their order information:

$user = User::with('orders')->find(1);

// output user information
echo $user->username;

// Output the user's order information
foreach ($user->orders as $order) {
    echo $order->order_no;
}

6.3 Advantages of the model - the model can help us better organize and manage data, making it easier and faster to add, delete, modify and query data.

  • The model can effectively check and verify the data to ensure the legality and integrity of the data.
  • Models can separate business logic and data operations, making the code clearer, easier to understand, and easier to maintain.
  • The model supports a variety of association relationships, such as one-to-one, one-to-many, many-to-many, etc., to facilitate data association query and operation.
  • The model supports advanced functions such as soft deletion and query scope, which can better meet complex business needs.

7. View

7.1 What is a view

  • What is a view? View (View) is the V in the MVC pattern, that is, the view model (View Model), which is the user interface in the web application. A view is usually an HTML file that contains markup and templates to display data.
  • What is the role of the view? The main function of the view is to present the data to the user, and present the data processed in the controller to the user in a readable way.
  • What is the use of the view? The method of using the view is to call the view template in the controller, pass the processed data to the view template, and then render the data into an HTML page by the view template. In ThinkPHP, use the $this->assign() method to pass data to the view template. For example:
// in the controller
public function index()
{
    $data = ['name' => 'Tom', 'age' => 18];
    $this->assign('data', $data);
    return $this->fetch();
}


<!-- In the view template -->
<h1>姓名:{$data.name}</h1>
<h1>Age: {$data.age}</h1>

7.2 Views in ThinkPHP

  • Views in ThinkPHP
    • output view using templating engine
//Use the template engine to output the view in the controller
public function index() {
  $this->assign('name', 'ThinkPHP');     
	return $this->fetch(); 
} 
// Output variables in the template file
<h1>Hello,{$name}!</h1> 
    • view inheritance
// parent template
<!DOCTYPE html> 
<html> 
  <head>     
    <meta charset="UTF-8">     
    <title>{% block title %}{% endblock %}</title> 
  </head> 
  <body>     
    {% block content %}
    {% endblock %} 
  </body> 
</html> 
//child template
{% extends 'layout.html' %} 
{% block title %}
child template
{% endblock %} 
{% block content %}     
<h1>Child template content</h1>
{% endblock %}
    • URL Generation in Views
//Generate the URL of the controller method
url('index/index'); 
//Generate the URL of the controller method, with parameters
url('index/detail', ['id' => 1]); 
//Generate the URL of the module/controller/method
url('admin/user/index'); 
//Generate external URL
url('http://www.thinkphp.cn'); 

7.3 Advantages of Views - Advantages of Views:

  • The view can separate the structure and logic of the page, making the code clearer and easier to understand.
  • Views can be reused to improve code reuse.
  • Views can be inherited and combined as needed, making the page design more flexible.
  • Views can improve page access speed and reduce server pressure through caching technology.
  • Views can use template engines to make page design easier and faster.

8. Database operation

8.1 Database configuration

  • Database configuration:
    • The configuration file is located at /config/database.php
    • Configure database connection information:
'hostname' => 'localhost', 
'database' => 'test', 
'username' => 'root', 
'password' => '123456', 
'hostport' => '', 
'params' => [], 
    • Use the Db class for database operations, such as queries:
$list = Db::name('user')->where('status', 1)->select(); 

8.2 Database connection

  • How to connect to the database
    • DSN method
    • configuration file method
  • Example of connecting to the database in DSN mode:
'db_type'   => 'mysql',
'db_host'   => '127.0.0.1',
'db_name'   => 'test',
'db_user'   => 'root',
'db_pwd'    => '',
'db_port'   => '3306',
'db_charset'=>    'utf8',
'db_params' =>  [
    \PDO::ATTR_CASE => \PDO::CASE_NATURAL
],
'db_debug'  =>  true,
'db_deploy_type'=> 0,
'db_rw_separate'=> false,
'db_master_num'=> 1,
'db_slave_no' => '',
'db_fields_strict'=> true,
'db_bind_param'=>   false,
'db_debug'  =>  true,
  • Example of connecting to the database in configuration file mode:
return [
    // database type
    'type'        => 'mysql',
    // server address
    'hostname'    => '127.0.0.1',
    // Database name
    'database'    => 'test',
    // database username
    'username'    => 'root',
    // database password
    'password'    => '',
    // database connection port
    'hostport'    => '3306',
    // database connection parameters
    'params'      => [],
    // The database encoding defaults to utf8
    'charset'     => 'utf8',
    // database table prefix
    'prefix'      => 'think_',
    // database debug mode
    'debug'       => true,
    // Database deployment method: 0 centralized (single server), 1 distributed (master-slave server)
    'deploy'      => 0,
    // Whether the database read and write is separated from the master-slave mode and is valid
    'rw_separate' => false,
    // Number of primary servers after read-write separation
    'master_num'  => 1,
    // Specify the serial number of the slave server
    'slave_no'    => '',
    // Whether to strictly check whether the field exists
    'fields_strict' => true,
    // data set return type
    'resultset_type' => 'collection',
    // Automatically write the timestamp field
    'auto_timestamp' => false,
    // The default time format after the time field is taken out
    'datetime_format' => 'Y-m-d H:i:s',
    // Do you need to perform SQL performance analysis
    'sql_explain' => false,
];

8.3 Addition, deletion, modification and query of database - adding operation of database

// Use the Query class for data insertion
Db::table('user')->insert([
    'name' => 'Zhang San',
    'age' => 20,
    'email' => '[email protected]'
]);

// use the model for data insertion
$user = new User;
$user->name = 'Li Si';
$user->age = 25;
$user->email = '[email protected]';
$user->save();
  • Database delete operation
// Use the Query class to delete data
Db::table('user')->where('id', 1)->delete();

// use the model for data deletion
$user = User::get(2);
$user->delete();
  • Database modification operations
// Use the Query class for data modification
Db::table('user')->where('id', 3)->update(['name' => '王五']);

// Use the model for data modification
$user = User::get(4);
$user->name = 'Zhao Liu';
$user->save();
  • Database query operation
// Use the Query class for data query
Db::table('user')->where('age', '>', 18)->select();

// Use the model for data query
User::where('age', '<', 30)->select();

Form syntax:

Operation method

Instructions

database addition

See example above

Database delete operation

See example above

Database modification operations

See example above

Database query operation

See example above

9. Summary

9.1 Advantages and disadvantages of ThinkPHP

  • 9.1 Advantages and disadvantages of ThinkPHP

Advantage

insufficient

1. Well-structured documentation and community support

1. The learning curve is relatively steep

2. Abundant extensions and plug-ins

2. Some functions require additional installation of extensions

3. The MVC architecture is clear and easy to understand

3. The performance is slightly lower than other frameworks

4. The database operation is convenient and fast

4. Some functions need to be implemented manually

5. High security, built-in functions such as preventing SQL injection

5. Some functions need to be implemented manually

9.2 Application scenarios of ThinkPHP

  • B2B e-commerce platform case developed using ThinkPHP
  • An enterprise-level OA system case developed using ThinkPHP
  • Case study of online education platform developed using ThinkPHP
  • Social networking site case developed using ThinkPHP
  • A case of logistics management system developed using ThinkPHP

sheet:

Application Scenario

the case

B2B e-commerce platform

A certain e-commerce company

Enterprise-level OA system

So-and-so OA

Online Education Platform

so-and-so education

Social networking site

so and so social

Logistics Management System

So-and-so logistics

9.3 Development Trend of ThinkPHP - Development Trend of ThinkPHP:

  • Pay more attention to performance optimization, such as using Swoole extension, etc.
  • Pay more attention to security, such as strengthening the defense against SQL injection, XSS attacks, etc.
  • Pay more attention to development efficiency, such as introducing more quick development tools and plug-ins
  • Pay more attention to the support of microservices and distributed architecture, such as the introduction of RPC, message queue and other technologies
  • Pay more attention to cross-platform and cross-language support, such as supporting the integration of multiple databases and multiple programming languages.

Guess you like

Origin blog.csdn.net/m0_46651458/article/details/129995108