Creating and Running a ThinkPHP 8 Project with ServBay
This article will guide you through using ServBay, a powerful local web development environment, to quickly create, configure, and run a PHP project based on the ThinkPHP 8 framework. ServBay offers a pre-configured PHP environment, web servers (Caddy or Nginx), and a range of databases, greatly simplifying the local setup process for ThinkPHP projects.
What Is ThinkPHP?
ThinkPHP is an open-source, fast, simple, object-oriented PHP development framework originating from China. Adhering to principles of simplicity and efficiency, it aims to provide developers with a convenient toolkit for building modern web applications. Thanks to its ease of use, comprehensive features (such as a powerful ORM, flexible routing, built-in templating engine, cache support, and more), and an active community, ThinkPHP enjoys widespread adoption across the Chinese PHP development sector.
Key Features and Advantages of ThinkPHP
- Simplicity and Efficiency: The framework is designed with clarity and maintainability in mind, allowing for easy understanding and high development efficiency.
- Comprehensive Functionality: Integrates commonly used web development components like MVC architecture, ORM, templating engine, caching, session management, authorization, form tokens, and more.
- Robust ORM: Offers a powerful and user-friendly object-relational mapping system, streamlining database operations.
- Flexible Routing: Supports multiple methods of route definition, catering to complex URL structures.
- Rich Ecosystem: Contains numerous extension libraries and plugins, as well as a vast and active developer community.
- Continual Updates: The framework evolves rapidly, keeping pace with PHP language changes and modern web development trends.
ThinkPHP is suitable for web projects of all sizes, from small applications to large-scale enterprise solutions.
Setting Up a ThinkPHP 8 Project with ServBay
ServBay provides an optimal environment for local ThinkPHP 8 development, including:
- Pre-installed PHP versions and popular extensions.
- Built-in web servers (Caddy or Nginx) for easy website configuration.
- Integrated database services: MySQL, PostgreSQL, MongoDB, Redis, Memcached, and more.
- Built-in Composer dependency manager.
This guide shows you how to harness ServBay’s features to set up your ThinkPHP 8 project in no time.
Prerequisites
Before you begin, please ensure the following are in place:
- Download and install ServBay on your macOS system.
- ServBay is running, and the required PHP version (ThinkPHP 8 requires PHP 8.0 or above) and necessary database services (such as MySQL, PostgreSQL, Redis, Memcached, etc.) are started. You can check and start these from the "Packages" tab in the ServBay control panel.
Creating a ThinkPHP Project
ServBay recommends managing all your local website files within the /Applications/ServBay/www
directory for optimal management.
Verify Composer Is Installed
Composer is already bundled with ServBay, so no further installation is necessary. Use the
composer --version
command in the ServBay terminal to verify.Create a ThinkPHP Project via Composer
Open your macOS terminal and run the following commands to create a new ThinkPHP 8 project in the ServBay web root directory:
bashcd /Applications/ServBay/www composer create-project topthink/think servbay-thinkphp-app
1
2This will create a new folder named
servbay-thinkphp-app
under/Applications/ServBay/www
, and download the core ThinkPHP 8 files and dependencies.Navigate to the Project Directory
Once the project is created, move into the directory:
bashcd /Applications/ServBay/www/servbay-thinkphp-app
1
Initializing Project Configuration
After project creation, some basic configuration is required.
Configure Database Connection Details
ThinkPHP’s database config is typically in
config/database.php
. Modify this file to match the database service you've started in ServBay.Here’s a sample configuration for ServBay’s default MySQL service:
php<?php // config/database.php return [ // Default database connection 'default' => env('database.driver', 'mysql'), // Database connections 'connections' => [ 'mysql' => [ // Database type 'type' => 'mysql', // Server address 'hostname' => env('database.hostname', '127.0.0.1'), // Database name 'database' => env('database.database', 'servbay_thinkphp_app'), // It’s recommended to create a dedicated DB for each project // Username 'username' => env('database.username', 'root'), // Password 'password' => env('database.password', 'password'), // ServBay default password, for local development only! // Port 'hostport' => env('database.hostport', '3306'), // ... other configs ... ], // ... other DB connections ... ], ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27Important Notes:
- Make sure you change the
database
value to the actual database you’ve created for this project (for example, create aservbay_thinkphp_app
database using ServBay’s phpMyAdmin or Adminer). - The default
root
MySQL password in ServBay ispassword
. This password is for local development use only — never use it in production! In production, always choose a strong password and create a user with minimal required privileges. - If you use a
.env
file for environment variables, ensure the settings there override the defaults inconfig/database.php
.
- Make sure you change the
Web Server Configuration
The ThinkPHP framework’s entry file is public/index.php
and depends on URL rewrite rules for routing. Since ThinkPHP’s routing requirements differ from a static site, you must use ServBay’s built-in rewrite rules.
In the website settings interface, choose ThinkPHP
from the Rewrite Rules dropdown menu and click Save.
For detailed website configuration instructions in ServBay, see Adding Your First Website.
Adding Sample Code
To test your website setup and ensure ThinkPHP’s basic routing works, let’s add a simple route and controller.
Edit /Applications/ServBay/www/servbay-thinkphp-app/route/app.php
and add the following code to define a basic GET route:
<?php
// route/app.php
use think\facade\Route;
// Define the servbay route, executes the callback on /servbay
Route::get('servbay', function () {
return 'Hello ServBay!';
});
// ... other routes ...
2
3
4
5
6
7
8
9
10
11
Accessing Your Website
Once the above steps are complete, open your web browser and visit your configured local domain and test route:
https://thinkphp.servbay.demo/servbay
If everything is correctly configured, you’ll see Hello ServBay!
displayed in your browser. This means that your ThinkPHP 8 project is now running successfully within the ServBay environment, with both the web server and PHP-FPM configured properly.
NoSQL Database Examples
ServBay includes popular NoSQL databases such as Memcached and Redis. ThinkPHP offers an abstraction layer for caching, which makes integrating these services as cache drivers straightforward.
Memcached Example
Install Memcached Extension
The Memcached extension is pre-installed with ServBay’s PHP package. Simply ensure the Memcached service is started via the "Packages" tab in the ServBay control panel.
Configure Memcached Cache
Edit the
config/cache.php
file to make ThinkPHP use Memcached as the cache driver:php<?php // config/cache.php return [ // Default cache driver 'default' => env('cache.driver', 'memcached'), // Cache connection configurations 'stores' => [ 'memcached' => [ // Cache type 'type' => 'memcached', // Server list 'host' => '127.0.0.1', // ServBay Memcached default address 'port' => 11211, // ServBay Memcached default port 'persistent' => false, 'expire' => 0, 'timeout' => 0, 'prefix' => '', ], // ... other cache configs ... ], ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23Using Memcached Cache in Code
In your controller or route callback, use ThinkPHP’s
Cache
Facade to interact with Memcached:php<?php use think\facade\Cache; use think\facade\Route; Route::get('/memcached-example', function () { // Set cache, valid for 600 seconds Cache::set('my_memcached_key', 'This value is from Memcached!', 600); // Get cache value $value = Cache::get('my_memcached_key'); return 'Value from Memcached: ' . $value; });
1
2
3
4
5
6
7
8
9
10
11
12
13Visit
https://thinkphp.servbay.demo/memcached-example
to test.
Redis Example
Install Redis Extension
The Redis extension is pre-installed with ServBay’s PHP package. Just be sure the Redis service is started via the "Packages" tab in ServBay.
Configure Redis Cache
Edit the
config/cache.php
file to set Redis as the cache driver:php<?php // config/cache.php return [ // Default cache driver 'default' => env('cache.driver', 'redis'), // Cache connection configurations 'stores' => [ 'redis' => [ // Cache type 'type' => 'redis', // Server address 'host' => env('cache.host', '127.0.0.1'), // ServBay Redis default address // Port 'port' => env('cache.port', 6379), // ServBay Redis default port // Password (default is empty for ServBay) 'password' => env('cache.password', ''), // No password by default 'select' => 0, 'timeout' => 0, 'expire' => 0, 'persistent' => false, 'prefix' => '', ], // ... other cache configs ... ], ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27Note: Redis provided by ServBay does not have a password set by default. If you've set one manually, remember to update the
password
field accordingly.Using Redis Cache in Code
Use the
Cache
Facade in your controller or route callback to interact with Redis:php<?php use think\facade\Cache; use think\facade\Route; Route::get('/redis-example', function () { // Set cache with no expiry (or specify expiry as the third parameter) Cache::set('my_redis_key', 'Hello from Redis!'); // Get cache value $value = Cache::get('my_redis_key'); return 'Value from Redis: ' . $value; });
1
2
3
4
5
6
7
8
9
10
11
12
13Visit
https://thinkphp.servbay.demo/redis-example
to test.
Relational Database Examples
ServBay is integrated with leading relational databases like MySQL and PostgreSQL. ThinkPHP’s ORM makes it easy to interact with these databases.
Using ThinkPHP Migration Tool
ThinkPHP offers a migration tool to manage changes to your database schema, which is a best practice for team collaboration and version control.
Install the Database Migration Tool
Use Composer in your project root to install ThinkPHP’s migration extension:
bashcd /Applications/ServBay/www/servbay-thinkphp-app composer require topthink/think-migration
1
2Create a Migration File
Use ThinkPHP’s CLI to generate a migration. For example, to create the
users
table:bashphp think migrate:create CreateUserTable
1This creates a new PHP file in the
database/migrations
folder (for example,20231027100000_create_user_table.php
).Edit the Migration File
Open the new file in
database/migrations
and define the structure of theusers
table in theup()
method:php<?php // database/migrations/YYYYMMDDHHMMSS_create_user_table.php use think\migration\Migrator; use think\migration\db\Column; class CreateUserTable extends Migrator { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * http://docs.phinx.org/en/latest/migrations.html#the-change-method * * The following commands can be used in this method and Phinx will * automatically reverse them when rolling back: * * createTable * renameTable * addColumn * addCustomColumn * renameColumn * addIndex * addForeignKey * createDatabase * renameDatabase * dropTable * dropColumn * dropIndex * dropForeignKey */ public function change() { // Create table using the createTable method $table = $this->table('users'); $table->addColumn('name', 'string', ['limit' => 50, 'comment' => 'User name']) ->addColumn('email', 'string', ['limit' => 100, 'comment' => 'Email address']) ->addIndex(['email'], ['unique' => true]) // Add unique index ->addTimestamps() // Add created_at and updated_at fields ->create(); // Execute creation } // You can alternatively define up() and down() if not using change() /* public function up() { $table = $this->table('users'); $table->addColumn('name', 'string', ['limit' => 50, 'comment' => 'User name']) ->addColumn('email', 'string', ['limit' => 100, 'comment' => 'Email address']) ->addIndex(['email'], ['unique' => true]) ->addTimestamps() ->create(); } public function down() { $this->dropTable('users'); } */ }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62Run the Database Migration
From the project root in the ServBay terminal, run the migration command to create the
users
table:bashphp think migrate:run
1Upon success, you'll see the new
users
table in your database.
MySQL Example
Assume MySQL service is running in ServBay, and you’ve configured the MySQL connection in config/database.php
as shown earlier.
Configure MySQL Connection
Refer to the previous "Initializing Project Configuration" section and ensure
config/database.php
has the correct MySQL settings.Insert User Data in Code
Use ThinkPHP’s
Db
Facade or ORM models. Here’s an example using theDb
Facade:php<?php use think\facade\Db; use think\facade\Route; Route::get('/mysql-add-user', function () { try { Db::table('users')->insert([ 'name' => 'ServBay Demo User', 'email' => '[email protected]', // Example brand email 'created_at' => date('Y-m-d H:i:s'), // Add timestamps manually if not auto-filled 'updated_at' => date('Y-m-d H:i:s'), ]); return 'User added successfully!'; } catch (\Exception $e) { return 'Error adding user: ' . $e->getMessage(); } });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Visit
https://thinkphp.servbay.demo/mysql-add-user
to test data insertion.Retrieve User Data in Code
Query data using the
Db
Facade or ORM:php<?php use think\facade\Db; use think\facade\Route; Route::get('/mysql-users', function () { $users = Db::table('users')->select(); // Fetch all users return json($users); // Return as JSON });
1
2
3
4
5
6
7
8Visit
https://thinkphp.servbay.demo/mysql-users
to view the data.
PostgreSQL Example
Suppose PostgreSQL is running in ServBay, and you’ve set its connection info in config/database.php
.
Configure PostgreSQL Connection
Edit
config/database.php
with the following (adapt as needed):php<?php // config/database.php (partial) return [ // ... other configs ... 'connections' => [ // ... MySQL settings ... 'pgsql' => [ // Database type 'type' => 'pgsql', // Server address 'hostname' => env('database.hostname', '127.0.0.1'), // Database name 'database' => env('database.database', 'servbay_thinkphp_app'), // It’s best to create a dedicated DB per project // Username 'username' => env('database.username', 'root'), // Password 'password' => env('database.password', 'password'), // ServBay default, for local development only! // Port 'hostport' => env('database.hostport', '5432'), // Default PostgreSQL port // ... other settings ... ], // ... other DB connections ... ], ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27Important: Like with MySQL, always create a dedicated PostgreSQL database for your project and set the correct name above. The default PostgreSQL
root
password is alsopassword
for ServBay — local use only.Insert User Data in Code
Use the
Db
Facade or ORM, specifying thepgsql
connection:php<?php use think\facade\Db; use think\facade\Route; Route::get('/pgsql-add-user', function () { try { Db::connect('pgsql')->table('users')->insert([ // Use pgsql connection 'name' => 'ServBay PgSQL User', 'email' => '[email protected]', // Example brand email // PostgreSQL timestamps may need manual insertion 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]); return 'PostgreSQL User added successfully!'; } catch (\Exception $e) { return 'Error adding PostgreSQL user: ' . $e->getMessage(); } });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18Visit
https://thinkphp.servbay.demo/pgsql-add-user
to test.Retrieve User Data in Code
Query via
Db
Facade with thepgsql
connection:php<?php use think\facade\Db; use think\facade\Route; Route::get('/pgsql-users', function () { $users = Db::connect('pgsql')->table('users')->select(); // Use pgsql connection return json($users); });
1
2
3
4
5
6
7
8Visit
https://thinkphp.servbay.demo/pgsql-users
to view PostgreSQL user data.
Summary
By following these steps, you’ve successfully used ServBay to create, configure, and run a ThinkPHP 8 project locally. You’ve learned how to use built-in Composer support for project creation, set up the Caddy web server’s routing for ThinkPHP, and connect to ServBay’s MySQL, PostgreSQL, Memcached, and Redis database services.
ServBay greatly streamlines the process of setting up local development environments for PHP frameworks like ThinkPHP, freeing you to focus on building your application’s business logic. You can now continue developing your ThinkPHP application and take full advantage of the powerful packages and features that ServBay offers.