Environment Setup and Installation
ThinkPHP 8 requires specific environment configurations. Ensure your system meets these prerequisites:
- PHP 8.0 or higher
- MySQL 5.7+
- Web server (Apache/Nginx recommended)
For local development, use a PHP environment manager like phpEnv:
# Download and install phpEnv
wget https://www.phpenv.cn/download/latest
sudo bash installer.sh
# Configure services
phpEnv configure --enable-apache --php-version=8.2 --mysql-version=8.0
# Start services
phpEnv start
After installation, verify PHP by accessing http://localhost in your browser.
ThinkPHP 8 Installation
Install ThinkPHP 8 using Composer:
# Install Composer if not already installed
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
# Create new ThinkPHP project
composer create-project topthink/think my-project
# Configure Composer to use domestic mirror for faster downloads
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
Start the development server:
cd my-project
php think run
Access your application at http://localhost:8000.
Project Structure and Configuration
ThinkPHP 8 follows PSR-4 standards with this directory structure:
app/- Application codeconfig/- Configurasion filespublic/- Web root directoryruntime/- Runtime files
Enable debug mode during development:
// .env file
APP_DEBUG = true
Database Configuration
Configure database connections in config/database.php:
// config/database.php
return [
'default' => env('database.driver', 'mysql'),
'connections' => [
'mysql' => [
'type' => 'mysql',
'hostname' => env('database.host', '127.0.0.1'),
'database' => env('database.name', 'demo'),
'username' => env('database.user', 'root'),
'password' => env('database.pass', 'password'),
'hostport' => env('database.port', '3306'),
'charset' => env('database.charset', 'utf8'),
]
]
];
Basic Database Operations
Perform database operations using the Query Builder:
// Select all records
$customers = Db::name('customers')->select();
// Insert new record
Db::name('customers')->insert([
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 30
]);
// Update record
Db::name('customers')->where('id', 1)->update(['age' => 31]);
// Delete record
Db::name('customers')->delete(1);
Model Layer
Create models for database interactions:
// app/model/Customer.php
namespace app\model;
use think\Model;
class Customer extends Model
{
// Define table name if different from model name
protected $name = 'customers';
// Define primary key
protected $pk = 'id';
}
Use models in controllers:
// app/controller/Customer.php
namespace app\controller;
use app\model\Customer;
class CustomerController
{
public function index()
{
$customers = Customer::select();
return json($customers);
}
}
Routing System
Define routes in route/app.php:
// route/app.php
use think\facade\Route;
Route::get('customers', 'Customer/index');
Route::post('customers', 'Customer/save');
Route::get('customers/:id', 'Customer/read');
Route::put('customers/:id', 'Customer/update');
Route::delete('customers/:id', 'Customer/delete');
Request Handling
Process incoming requests:
// app/controller/Customer.php
namespace app\controller;
use think\Request;
class CustomerController
{
public function save(Request $request)
{
$data = $request->post();
// Validate and save data
return json(['status' => 'success']);
}
}
Validation
Create validation rules:
// app/validate/Customer.php
namespace app\validate;
use think\Validate;
class Customer extends Validate
{
protected $rule = [
'name' => 'require|max:25',
'email' => 'email',
'age' => 'number|between:18,60'
];
protected $message = [
'name.require' => 'Name is required',
'email.email' => 'Email format is incorrect',
'age.between' => 'Age must be between 18 and 60'
];
}
Use validation in controllers:
// app/controller/Customer.php
namespace app\controller;
use app\validate\Customer as CustomerValidate;
class CustomerController
{
public function save()
{
$validate = new CustomerValidate();
$data = input('post.');
if (!$validate->check($data)) {
return json(['status' => 'error', 'message' => $validate->getError()]);
}
// Process valid data
}
}
Middleware
Create custom middleware:
// app/middleware/Auth.php
namespace app\middleware;
class Auth
{
public function handle($request, \Closure $next)
{
if (!session('user')) {
return redirect('login');
}
return $next($request);
}
}
Register middleware in middleware.php:
// app/middleware.php
return [
app\middleware\Auth::class
];
Views and Templates
Create views in the view/ directory:
// app/controller/Customer.php
namespace app\controller;
class CustomerController
{
public function index()
{
$customers = Customer::select();
return view('customer/index', ['customers' => $customers]);
}
}
Create the corresponding view file:
// view/customer/index.html
<html>
<head><title>Customers</title></head>
<body>
<h1>Customer List</h1>
<table>
<tr><th>Name</th><th>Email</th><th>Age</th></tr>
{foreach $customers as $customer}
<tr>
<td>{$customer.name}</td>
<td>{$customer.email}</td>
<td>{$customer.age}</td>
</tr>
{/foreach}
</table>
</body>
</html>
Session and Cache
Manage sessions:
// Set session
session('user', ['id' => 1, 'name' => 'John Doe']);
// Get session
$user = session('user');
// Clear session
session(null);
Use cache for performance:
// Set cache
Cache::set('config', ['key' => 'value'], 3600);
// Get cache
$config = Cache::get('config');
// Delete cache
Cache::delete('config');
File Uploads
Handle file uploads:
// app/controller/Upload.php
namespace app\controller;
class Upload
{
public function save()
{
$file = request()->file('image');
$savename = Filesystem::putFile('images', $file);
return json(['savename' => $savename]);
}
}
Pagination
Implement pagination:
// app/controller/Customer.php
namespace app\controller;
class CustomerController
{
public function index()
{
$list = Customer::paginate(10);
return view('customer/index', ['list' => $list]);
}
}
In the view:
// view/customer/index.html
<div>{$list->render()}</div>
Advanced Features
ThinkPHP 8 supports advanced features like:
- RESTful API development
- WebSocket support
- Queue system
- Task scheduling
- Event system