用webman重構一下

my38778570發表於2022-11-24

安裝

webman 要求PHP >= 7.2

composer安裝

1、去掉composer代理
composer config -g --unset repos.packagist
2、建立專案

composer create-project workerman/webman
3、執行

進入webman目錄

debug方式執行(用於開發除錯)

php start.php start

daemon方式執行(用於正式環境)

php start.php start -d

windows使用者用 雙擊windows.bat 或者執行 php windows.php 啟動

4、訪問

瀏覽器訪問 http://ip地址:8787

webman配置https證照

配置資料庫

資料庫配置檔案位置為 config/database.php

<?php
return [
    // 預設資料庫
    'default' => 'mysql',
    // 各種資料庫配置
    'connections' => [

        'mysql' => [
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'port' => 3306,
            'database' => 'webman',
            'username' => 'webman',
            'password' => 'webman',
            'unix_socket' => '',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => 'webm_',
            'strict' => false, //是否嚴格模式
            'engine' => null,
        ],
    ],


];

Migration資料庫遷移工具 Phinx

安裝

composer require robmorgan/phinx

在你專案目錄中建立目錄 db/migrations ,並給予充足許可權。這個目錄將是你遷移指令碼放置的地方,並且應該被設定為可寫許可權。

安裝後,Phinx 現在可以在你的專案中執行初始化

vendor/bin/phinx init

檢查是否建立成功

 # !!! 這個測試透過,並沒有測試 資料庫設連結是否正確。
[root@iZvixj0oze6411Z webman]# vendor/bin/phinx test

### 預設的環境是開發環境,這個測試資料庫的連結是否正確
[root@iZvixj0oze6411Z webman]# vendor/bin/phinx test  -e development
Phinx by CakePHP - https://phinx.org.

using config file phinx.php
using config parser php
validating environment development
success!

建立目錄

webman基本使用

webman基本使用

[root@iZvixj0oze6411Z webman]# php vendor/bin/phinx create UserMigration
Phinx by CakePHP - https://phinx.org.

using config file phinx.php
using config parser php
using migration paths 
 - /www/wwwroot/webman/db/migrations
using seed paths 
 - /www/wwwroot/webman/db/seeds
using migration base class Phinx\Migration\AbstractMigration
using default template
created db/migrations/20221124030111_user_migration.php

webman基本使用

    public function change()
    {
        $table = $this->table('webm_user');
        // 新增幾個欄位
        $table
            ->addColumn('name', 'string', ["length" => "30", "default" => "", "comment" => '使用者名稱'])
            ->addColumn('phone', 'string', ["length" => "30"])
            ->addColumn('sex', 'integer', ["length" => "4"])
            ->addIndex(array('name'), array('unique' => true, 'name' => 'idx_users_name'))
            ->addIndex(array('phone'), array('unique' => false, 'name' => 'idx_users_phone'))
            ->create();
    }

執行

[root@iZvixj0oze6411Z webman]# php vendor/bin/phinx migrate
Phinx by CakePHP - https://phinx.org.

using config file phinx.php
using config parser php
using migration paths 
 - /www/wwwroot/webman/db/migrations
using seed paths 
 - /www/wwwroot/webman/db/seeds
warning no environment specified, defaulting to: development
using adapter mysql
using database webman
ordering by creation time

 == 20221124024949 MyNewMigration: migrating 
 == 20221124024949 MyNewMigration: migrated 0.0085s

 == 20221124030111 UserMigration: migrating 
 == 20221124030111 UserMigration: migrated 0.0540s

All Done. Took 0.0783s

新增一個欄位

[root@iZvixj0oze6411Z webman]# php vendor/bin/phinx create User02Migration
Phinx by CakePHP - https://phinx.org.

using config file phinx.php
using config parser php
using migration paths 
 - /www/wwwroot/webman/db/migrations
using seed paths 
 - /www/wwwroot/webman/db/seeds
using migration base class Phinx\Migration\AbstractMigration
using default template
created db/migrations/20221124032327_user_02_migration.php
    public function change()
    {
        $table = $this->table('webm_user');

        $table
            ->addColumn('created_at', 'timestamp')
            ->addColumn('updated_at', 'timestamp')
            ->addColumn('deleted_at', 'timestamp')
            ->save();
    }

使用建議

遷移檔案一旦程式碼合併後不允許再次修改,出現問題必須新建修改或者刪除操作檔案進行處理。

webman基本使用

webman基本使用

資料庫

安裝

composer require -W psr/container ^1.1.1 illuminate/database illuminate/pagination illuminate/events symfony/var-dumper

user 模型關聯

<?php

namespace app\model;

use support\Model;

class User extends Model
{
    protected $with = [
        'user_token'
    ];
    /**
     * 與模型關聯的表名
     *
     * @var string
     */
    protected $table = 'user';

    /**
     * 重定義主鍵,預設是id
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 指示是否自動維護時間戳
     *
     * @var bool
     */
    public $timestamps = true;

    public function user_token()
    {
        return $this->hasOne(UserToken::class, 'user_id', 'id');
    }

}

驗證器

路由

<?php

use Webman\Route;

Route::group('/admin', function () {
    Route::any('/login/index', [app\admin\controller\LoginController::class, 'index']);
});

Route::group('/admin', function () {
    Route::any('/user/index', [app\admin\controller\UserController::class, 'index']);
    Route::any('/user/store', [app\admin\controller\UserController::class, 'store']);
    Route::any('/user/update', [app\admin\controller\UserController::class, 'update']);
    Route::any('/user/{id}', [app\admin\controller\UserController::class, 'show']);
    Route::any('/user/delete/{id}', [app\admin\controller\UserController::class, 'delete']);
})->middleware([
    app\middleware\AuthCheckTest::class,
]);

控制器

webman基本使用

<?php

namespace app\admin\controller;

use app\model\User;
use support\Request;
use support\Response;

class UserController
{
    public function index(Request $request)
    {
        $session = $request->session();
        $user = $session->get('user');
        var_dump('登入使用者:' . $user->id);
        $per_page = 2;
        $users = User::paginate($per_page, '*', 'page', $request->input('page'));
        return json(['code' => 0, 'msg' => '獲取成功', 'data' => $users]);
    }


    public function store(Request $request)
    {
        // 驗證請求
        $user = new User();
        $user->name = $request->get('name') . date('Y-m-d H:i:s');
        $user->phone = $request->get('phone');
        $user->sex = $request->get('sex');
        $user->save();
        return json(['code' => 0, 'msg' => '新增成功']);
    }
    public function update(Request $request)
    {
        $user = User::find($request->get('id'));
        $user->name = $request->get('name') . '修改了' . date('Y-m-d H:i:s');
        $user->save();
        return json(['code' => 0, 'msg' => '儲存成功']);
    }
    public function show($id)
    {
        $model = User::find($id);
        return json(['code' => 0, 'msg' => '獲取成功', 'data' => $model]);
    }
    public function delete($id)
    {
        $model = User::find($id);
        $model->delete();
        return json(['code' => 0, 'msg' => '刪除成功']);
    }
}

token驗證

[root@iZvixj0oze6411Z webman]# php vendor/bin/phinx create UserTokenMigration
Phinx by CakePHP - https://phinx.org.

using config file phinx.php
using config parser php
using migration paths 
 - /www/wwwroot/webman/db/migrations
using seed paths 
 - /www/wwwroot/webman/db/seeds
using migration base class Phinx\Migration\AbstractMigration
using default template
created db/migrations/20221124064101_user_token_migration.php
    public function change()
    {
        $table = $this->table('webm_user_token');
        // 新增幾個欄位
        $table
            ->addColumn('user_id', 'integer', ["default" => 0, "comment" => '使用者id'])
            ->addColumn('token', 'string', ["length" => "32"])
            ->addIndex(array('user_id'), array('unique' => false, 'name' => 'idx_user_id'))
            ->addIndex(array('token'), array('unique' => false, 'name' => 'idx_token'))
            ->create();
    }
[root@iZvixj0oze6411Z webman]# php vendor/bin/phinx migrate
Phinx by CakePHP - https://phinx.org.

using config file phinx.php
using config parser php
using migration paths 
 - /www/wwwroot/webman/db/migrations
using seed paths 
 - /www/wwwroot/webman/db/seeds
warning no environment specified, defaulting to: development
using adapter mysql
using database webman
ordering by creation time

 == 20221124064101 UserTokenMigration: migrating 
 == 20221124064101 UserTokenMigration: migrated 0.0589s

user_token model

<?php

namespace app\model;

use support\Model;

class UserToken extends Model
{
    /**
     * 與模型關聯的表名
     *
     * @var string
     */
    protected $table = 'user_token';

    /**
     * 重定義主鍵,預設是id
     *
     * @var string
     */
    protected $primaryKey = 'id';

    public $timestamps = false;


}

登入

<?php

namespace app\admin\controller;

use app\model\User;
use app\model\UserToken;
use support\Request;
use support\Response;

class LoginController
{
    public function index(Request $request)
    {
        $model = User::find(9);
        $user_token_model = new UserToken();
        $user_token_model->token = md5($model->id);
        $user_token_model->user_id = $model->id;
        $user_token_model->save();
        return json(['code' => 0, 'msg' => '登入成功', 'token' => md5($model->id)]);
    }

}

登入中介軟體

<?php

namespace app\middleware;

use app\model\User;
use app\model\UserToken;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AuthCheckTest implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $token = $request->get('token');
        var_dump($token);
        if (empty($token)) {
            return json(['code' => 0, 'msg' => '請先登入1']);
        }
        $user_token_model = UserToken::where('token', $token)->first();
        if (empty($user_token_model)) {
            return json(['code' => 0, 'msg' => '請先登入2']);
        }
        $model = User::find($user_token_model->user_id);
        if (empty($model)) {
            return json(['code' => 0, 'msg' => '非法操作']);
        }
        $session = $request->session();
        $session->set('user', $model);
        // 請求繼續向洋蔥芯穿越
        return $handler($request);
    }
}

訪問

ip:8787/admin/login/index
ip:8787/admin/user/index?page=3&token=45c48cce2e2d7fbdea1afc51c7c6ad26
ip:8787/admin/user/store?name=webman4&phone=10010&sex=1
ip:8787/admin/user/update?id=4&name=tony
ip:8787/admin/user/1
ip:8787/admin/user/delete/1

用webman重構一下

ab壓測

安裝

yum -y install httpd-tools
ab -V

現在我們假設有1000個請求(-n),併發量為100(-c)

ab -n 1000 -c 100  http://ip:8787/admin/user/index?page=3&token=45c48cce2e2d7fbdea1afc51c7c6ad26

阿里雲1核2G壓測結果

用webman重構一下

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章