先选择合适的 php 版本,建议8.1+
安装 composer
wget https://getcomposer.org/download/2.7.9/composer.phar
创建项目
composer create-project workerman/webman .
安装常用扩展
composer require webman/redis-queue vlucas/phpdotenv webman/event workerman/crontab webman/console illuminate/database symfony/var-dumper laravel/serializable-closure
常用配置文件
# .env
DB_HOST = 127.0.0.1
DB_PORT = 3306
DB_NAME = test
DB_USER = foo
DB_PASSWORD = 123456
REDIS_HOST = 127.0.0.1
REDIS_PORT = 6379
REDIS_PASS = 123456
REDIS_DB = 1
# config/database.php
return [
// 默认数据库
'default' => 'mysql',
// 各种数据库配置
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_NAME', 'webman'),
'username' => env('DB_USER', 'root'),
'password' => env('DB_PASSWORD', '123456'),
'unix_socket' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
'options' => [
\PDO::ATTR_TIMEOUT => 3
]
],
],
];
# config/redis.php
return [
'default' => [
'host' => env('DB_HOST', '127.0.0.1'),
'password' => env('DB_HOST', null),
'port' => env('DB_HOST', '6379'),
'database' => env('DB_HOST', '0'),
],
];
数据库常用方法
use support\Db;
# 获取所有结果
Db::table('user')->select('name', 'email as user_email')->get();
# 获取一行
Db::table('users')->where('name', 'John')->first();
# 获取某个值
Db::table('users')->where('name', 'John')->value('email');
# 分块处理
Db::table('users')->orderBy('id')->chunkById(100, function ($users) {foreach ($users as $user) {}});
# 原生表达式
Db::table('orders')->selectRaw('price * ? as price_with_tax', [1.0825])->get();
# 左查询
Db::table('users')->leftJoin('posts', 'users.id', '=', 'posts.user_id')->get();
# 查询条件
Db::table('users')->where('name', 'like', 'T%')->get();
# IN查询
Db::table('users')->whereIn('id', [1, 2, 3])->get();
# 插入数据
Db::table('users')->insertGetId([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0]
]);
# 调试 composer require symfony/var-dumper
Db::table('users')->where('votes', '>', 100)->dd(); -- 只打印
Db::table('users')->where('votes', '>', 100)->dump();
Redis 常用方法
use support\Redis;
Redis::append($key, $value)
Redis::bitCount($key)
Redis::decr($key, $value)
Redis::decrBy($key, $value)
Redis::get($key)
Redis::getBit($key, $offset)
Redis::getRange($key, $start, $end)
Redis::getSet($key, $value)
Redis::incr($key, $value)
Redis::incrBy($key, $value)
Redis::incrByFloat($key, $value)
Redis::mGet(array $keys)
Redis::getMultiple(array $keys)
Redis::mSet($pairs)
Redis::mSetNx($pairs)
Redis::set($key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
Redis::setBit($key, $offset, $value)
Redis::setEx($key, $ttl, $value)
Redis::pSetEx($key, $ttl, $value)
Redis::setNx($key, $value)
Redis::setRange($key, $offset, $value)
Redis::strLen($key)
Redis::del(...$keys)
Redis::exists(...$keys)
Redis::expire($key, $ttl)
Redis::expireAt($key, $timestamp)
Redis::select($dbIndex)
日志常用方法
use support\Log;
Log::log($level, $message, array $context = [])
Log::debug($message, array $context = [])
Log::info($message, array $context = [])
Log::notice($message, array $context = [])
Log::warning($message, array $context = [])
Log::error($message, array $context = [])
Log::critical($message, array $context = [])
Log::alert($message, array $context = [])
Log::emergency($message, array $context = [])
测试的表
CREATE TABLE `user` (
`user_id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_code` bigint NOT NULL COMMENT '用户唯一编号',
`user_name` varchar(200) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '登录用户名',
`password` varchar(150) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '登录密码',
`salt` varchar(30) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '盐加密',
`mobile` char(20) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号码',
`email` varchar(200) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '邮箱地址',
`status` tinyint(1) DEFAULT '1' COMMENT '状态: 1正常 2禁用',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`is_del` tinyint(1) NOT NULL DEFAULT '1' COMMENT '有效标识: 1正常 0删除',
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_code` (`user_code`),
UNIQUE KEY `user_name` (`user_name`),
UNIQUE KEY `mobile` (`mobile`),
UNIQUE KEY `email` (`email`),
KEY `create_time` (`create_time`),
KEY `update_time` (`update_time`),
KEY `is_del` (`is_del`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='用户主表';
CREATE TABLE `user_info` (
`user_info_id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_code` bigint NOT NULL COMMENT '用户唯一编号',
`nickname` varchar(200) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '昵称',
`gender` tinyint(1) DEFAULT '3' COMMENT '性别:1男 2女 3保密',
`avatar` varchar(150) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '头像',
`birthday` date DEFAULT NULL COMMENT '出生日期',
`login_ip` varchar(20) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '最近登录IP',
`login_time` datetime DEFAULT NULL COMMENT '最近登录时间',
`order_sort` int DEFAULT '0' COMMENT '排序号',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`user_info_id`) USING BTREE,
UNIQUE KEY `user_code` (`user_code`),
KEY `create_time` (`create_time`),
KEY `update_time` (`update_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=COMPACT COMMENT='用户信息表';
测试的代码:
// {
// "table": "user",
// "where": ["user_id","<","2"],
// "limit": 1,
// "field": ["user_code"],
// "order": "user_id"
// }
public function index(Request $request)
{
$table = $request->input('table', '');
$field = $request->input('field', ['*']);
$where = $request->input('where', []);
$limit = $request->input('limit', '10');
$order = $request->input('order', '');
$data = Db::table($table)->select($field)->where(...$where)->orderBy($order)->limit($limit)->get();
return json(['code' => 0, 'msg' => 'ok', 'table' => $table, 'data' => $data]);
}