code-generation(代碼生成組件)
EasySwoole
代碼生成組件,使用命令行就可以一鍵生成業務通用代碼,支持生成的代碼如下:
- 一鍵生成
項目初始化 baseController、baseModel、baseUnitTest
; - 一鍵生成
表 Model,自帶屬性注釋
; - 一鍵生成
表 curd 控制器,自帶 5 個 curd 方法
; - 一鍵生成
控制器單元測試用例,測試 5 個 curd 方法
。
組件要求
- easyswoole/trigger: ^1.0
- easyswoole/socket: ^1.0
- easyswoole/orm: ^1.4
- nette/php-generator: ^3.2
- easyswoole/http-annotation: ^1.4
- php-curl-class/php-curl-class: ^8.5
- easyswoole/command: ^1.1
安裝方法
composer require easyswoole/code-generation=1.x
倉庫地址
easyswoole/code-generation 1.x
基本使用
<?php
/**
* Created by PhpStorm.
* User: tioncico
* Date: 2020-05-20
* Time: 10:26
*/
include __DIR__ . "/vendor/autoload.php";
\EasySwoole\EasySwoole\Core::getInstance()->initialize()->globalInitialize();
go(function () {
// 生成基礎類
$generation = new \EasySwoole\CodeGeneration\InitBaseClass\Controller\ControllerGeneration();
$generation->generate();
$generation = new \EasySwoole\CodeGeneration\InitBaseClass\UnitTest\UnitTestGeneration();
$generation->generate();
$generation = new \EasySwoole\CodeGeneration\InitBaseClass\Model\ModelGeneration();
$generation->generate();
$mysqlConfig = new \EasySwoole\ORM\Db\Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
// 獲取連接
$connection = new \EasySwoole\ORM\Db\Connection($mysqlConfig);
$tableName = 'user_list';
$codeGeneration = new EasySwoole\CodeGeneration\CodeGeneration($tableName, $connection);
// 生成model
$codeGeneration->generationModel("\\User");
// 生成controller
$codeGeneration->generationController("\\Api\\User", null);
// 生成unitTest
$codeGeneration->generationUnitTest("\\User", null);
});
\Swoole\Timer::clearAll();
EasySwoole\CodeGeneration\CodeGeneration
方法可自行查看,代碼很簡單。
命令行使用
由于命令行特殊的特性,命令行功能支持并不完善,如果想要體驗全部功能,請使用 EasySwoole\CodeGeneration\CodeGeneration
生成,或參考 EasySwoole\CodeGeneration\CodeGeneration
代碼生成。
注冊命令
在 bootstrap事件
中使用 Di
注入配置項:
<?php
/**
* Created by PhpStorm.
* User: tioncico
* Date: 2020-05-21
* Time: 11:20
*/
\EasySwoole\EasySwoole\Core::getInstance()->initialize();
$mysqlConfig = new \EasySwoole\ORM\Db\Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
// 獲取連接
$connection = new \EasySwoole\ORM\Db\Connection($mysqlConfig);
// 注入mysql連接
\EasySwoole\Component\Di::getInstance()->set('CodeGeneration.connection',$connection);
// 直接注入mysql配置對象
\EasySwoole\Component\Di::getInstance()->set('CodeGeneration.connection',$mysqlConfig);
// 直接注入mysql配置項
// \EasySwoole\Component\Di::getInstance()->set('CodeGeneration.connection',\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
// 注入執行目錄項,后面的為默認值,initClass不能通過注入改變目錄
\EasySwoole\Component\Di::getInstance()->set('CodeGeneration.modelBaseNameSpace',"App\\Model");
\EasySwoole\Component\Di::getInstance()->set('CodeGeneration.controllerBaseNameSpace',"App\\HttpController");
\EasySwoole\Component\Di::getInstance()->set('CodeGeneration.unitTestBaseNameSpace',"UnitTest");
\EasySwoole\Component\Di::getInstance()->set('CodeGeneration.rootPath',getcwd());
\EasySwoole\EasySwoole\Command\CommandRunner::getInstance()->commandContainer()->set(new \EasySwoole\CodeGeneration\GenerationCommand());
即可使用命令生成。
php easyswoole.php generation
______ _____ _
| ____| / ____| | |
| |__ __ _ ___ _ _ | (___ __ __ ___ ___ | | ___
| __| / _` | / __| | | | | \___ \ \ \ /\ / / / _ \ / _ \ | | / _ \
| |____ | (_| | \__ \ | |_| | ____) | \ V V / | (_) | | (_) | | | | __/
|______| \__,_| |___/ \__, | |_____/ \_/\_/ \___/ \___/ |_| \___|
__/ |
|___/
php ./bin/code-generator all tableName modelPath [controllerPath] [unitTestPath]
php ./bin/code-generator init
php ./bin/code-generator all user_list \\User \\Api\\\User \\User
獨立使用
生成器流程說明
- 通過
\EasySwoole\ORM\Utility\TableObjectGeneration
,傳入\EasySwoole\ORM\Db\Connection
連接對象,通過generationTable
方法獲取表結構對象; - 實例化類生成器配置,配置命名空間、生成文件路徑、類名等(詳情看下面);
- 實例化生成器對象,調用
generate
方法生成。
生成器基礎配置項
-
extendClass
繼承類,默認為\EasySwoole\ORM\AbstractModel::class
- directory 生成路徑,生成路徑默認為
rootPath+namespace
對應路徑,namespace路徑將自動通過composer.json->(autoload/autoload-dev)['psr-4']
配置目錄生成,如果沒有則默認為根目錄 - namespace 命名空間配置.
- className 類名
- rootPath 項目根目錄,默認為執行目錄.
獲取數據表結構
所有生成器都依賴于數據表結構對象EasySwoole\ORM\Utility\Schema\Table
<?php
$mysqlConfig = new \EasySwoole\ORM\Db\Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
//獲取連接
$connection = new \EasySwoole\ORM\Db\Connection($mysqlConfig);
$tableName = 'user_list';
//獲取數據表結構對象
$tableObjectGeneration = new \EasySwoole\ORM\Utility\TableObjectGeneration($connection, $tableName);
$schemaInfo = $tableObjectGeneration->generationTable();
Model生成
Model配置項說明
- extendClass 繼承類,默認為
\EasySwoole\ORM\AbstractModel::class
- directory 生成路徑,生成路徑默認為
rootPath+namespace
對應路徑,namespace路徑將自動通過composer.json->(autoload/autoload-dev)['psr-4']
配置目錄生成,如果沒有則默認為根目錄 - namespace 命名空間配置.默認為
App\Model
- className 類名,Model配置無效,強制為
realTableName+fileSuffix
- rootPath 項目根目錄,默認為執行目錄.
- tablePre 表前綴,如果有配置,es_user 表=> UserModel
- table 表結構對象
- realTableName 真實表名,通過下劃線形式轉為大駝峰,自動轉化.用于生成最后的類名和文件名.
- fileSuffix 文件后綴,默認為
Model
,用于生成最后的類名和文件名. - ignoreString 默認為['list', 'log'], //生成時忽略表名存在的字符,例如user_list將生成=>UserModel
Model生成示例:
<?php
/**
* Created by PhpStorm.
* User: tioncico
* Date: 2020-05-20
* Time: 10:26
*/
include "./vendor/autoload.php";
\EasySwoole\EasySwoole\Core::getInstance()->initialize()->globalInitialize();
go(function () {
$mysqlConfig = new \EasySwoole\ORM\Db\Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
//獲取連接
$connection = new \EasySwoole\ORM\Db\Connection($mysqlConfig);
$tableName = 'user_list';
//獲取數據表結構對象
$tableObjectGeneration = new \EasySwoole\ORM\Utility\TableObjectGeneration($connection, $tableName);
$schemaInfo = $tableObjectGeneration->generationTable();
$tablePre = '';//表前綴
$path = "App\\Model";
$extendClass = \EasySwoole\ORM\AbstractModel::class;
$modelConfig = new \EasySwoole\CodeGeneration\ModelGeneration\ModelConfig($schemaInfo, $tablePre, "{$path}", $extendClass);
$modelConfig->setRootPath(EASYSWOOLE_ROOT);//設置項目運行目錄,默認為當前執行腳本目錄.
$modelConfig->setIgnoreString(['list', 'log']);//生成時忽略表名存在的字符,例如user_list將生成=>UserModel
$modelGeneration = new \EasySwoole\CodeGeneration\ModelGeneration\ModelGeneration($modelConfig);
$result = $modelGeneration->generate();
var_dump($result);//生成成功返回生成文件路徑,否則返回false
});
\Swoole\Timer::clearAll();
Model方法
Model方法默認生成一個GetList
方法,用于獲取列表.
<?php
public function getList(int $page = 1, int $pageSize = 10, string $field = '*'): array
{
$list = $this
->withTotalCount()
->order($this->schemaInfo()->getPkFiledName(), 'DESC')
->field($field)
->page($page, $pageSize)
->all();
$total = $this->lastQueryResult()->getTotalCount();;
return ['total' => $total, 'list' => $list];
}
可參考EasySwoole\CodeGeneration\ModelGeneration\Method\GetList
自定義其他方法.再進行注入即可.
addGenerationMethod(new \EasySwoole\CodeGeneration\ModelGeneration\Method\GetList($modelGeneration));
Controller生成
Controller 配置項說明
Controller配置項繼承與Model配置項
- modelClass Model類類名(包含命名空間),Controller生成依賴于Model,所以需要傳入Model類類名
- authSessionName 權限驗證session參數名,比如在需要用戶登錄的控制器方法中,都需要傳入session字段名用于驗權,controller將在生成方法時自動生成驗證這個session參數的注解,默認為空
- extendClass 繼承類,默認為
\EasySwoole\HttpAnnotation\AnnotationController
- directory 生成路徑,生成路徑默認為
rootPath+namespace
對應路徑,namespace路徑將自動通過composer.json->(autoload/autoload-dev)['psr-4']
配置目錄生成,如果沒有則默認為根目錄 - namespace 命名空間配置.默認為
App\\HttpController
- className 類名,Model配置無效,強制為
realTableName+fileSuffix
- fileSuffix 文件后綴,默認為空,用于生成最后的類名和文件名.
- ignoreString 默認為['list', 'log'], //生成時忽略表名存在的字符,例如user_list將生成=>User
controller生成示例
<?php
/**
* Created by PhpStorm.
* User: tioncico
* Date: 2020-05-20
* Time: 10:26
*/
include "./vendor/autoload.php";
\EasySwoole\EasySwoole\Core::getInstance()->initialize()->globalInitialize();
go(function () {
$mysqlConfig = new \EasySwoole\ORM\Db\Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
//獲取連接
$connection = new \EasySwoole\ORM\Db\Connection($mysqlConfig);
$tableName = 'user_list';
//獲取數據表結構對象
$tableObjectGeneration = new \EasySwoole\ORM\Utility\TableObjectGeneration($connection, $tableName);
$schemaInfo = $tableObjectGeneration->generationTable();
$tablePre = '';//表前綴
$path = "App\\HttpController";
$extendClass = \EasySwoole\HttpAnnotation\AnnotationController::class;
$modelClass = \App\Model\UserModel::class;//$modelGeneration->getConfig()->getNamespace() . '\\' . $modelGeneration->getClassName();
$controllerConfig = new \EasySwoole\CodeGeneration\ControllerGeneration\ControllerConfig($modelClass, $schemaInfo, $tablePre, "{$path}", $extendClass);
$controllerConfig->setRootPath(EASYSWOOLE_ROOT);
$controllerGeneration = new \EasySwoole\CodeGeneration\ControllerGeneration\ControllerGeneration($controllerConfig);
$result = $controllerGeneration->generate();
var_dump($result);
});
\Swoole\Timer::clearAll();
Controller方法.
Controller支持了5個方法,Add
,Delete
,GetList
,GetOne
,Update
.
自定義其他方法可參考Model方法自定義.
unitTest
單元測試生成器生成.生成后的文件為作者本人自定義風格代碼,需要依賴于BaseUnitTest
<?php
namespace UnitTest;
use Curl\Curl;
use EasySwoole\EasySwoole\Core;
use PHPUnit\Framework\TestCase;
/**
* BaseTest
* Class BaseTest
* Create With ClassGeneration
*/
class BaseTest extends TestCase
{
public static $isInit = 0;
/** @var Curl */
public $curl;
public $apiBase = 'http://127.0.0.1:9501';
public $modelName;
public function request($action, $data = [], $modelName = null)
{
$modelName = $modelName ?? $this->modelName;
$url = $this->apiBase . '/' . $modelName . '/' . $action;
$curl = $this->curl;
$curl->post($url, $data);
if ($curl->response) {
// var_dump($curl->response);
} else {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "
";
}
$this->assertTrue(!!$curl->response);
$this->assertEquals(200, $curl->response->code, $curl->response->msg);
return $curl->response;
}
public function setUp()
{
if (self::$isInit == 1) {
return true;
}
require_once dirname(__FILE__, 2) . '/vendor/autoload.php';
defined('EASYSWOOLE_ROOT') or define('EASYSWOOLE_ROOT', dirname(__FILE__, 2));
require_once dirname(__FILE__, 2) . '/EasySwooleEvent.php';
Core::getInstance()->initialize()->globalInitialize();
self::$isInit = 1;
$this->curl = new Curl();
}
}
unitTest配置項說明
unitTest配置項繼承于Model配置項
- modelClass Model類類名(包含命名空間),UnitTest生成依賴于Model,所以需要傳入Model類類名
- ControllerClass ControllerClass類類名(包含命名空間),UnitTest生成依賴于ControllerClass,所以需要傳入ControllerClass類類名
- extendClass 繼承類,默認為
\PHPUnit\Framework\TestCase
- directory 生成路徑,生成路徑默認為
rootPath+namespace
對應路徑,namespace路徑將自動通過composer.json->(autoload/autoload-dev)['psr-4']
配置目錄生成,如果沒有則默認為根目錄 - namespace 命名空間配置.默認為
UnitTest
- className 類名,Model配置無效,強制為
realTableName+fileSuffix
- fileSuffix 文件后綴,默認為
Test
,用于生成最后的類名和文件名. - ignoreString 默認為['list', 'log'], //生成時忽略表名存在的字符,例如user_list將生成=>UserTest
unitTest生成示例
<?php
/**
* Created by PhpStorm.
* User: tioncico
* Date: 2020-05-20
* Time: 10:26
*/
include "./vendor/autoload.php";
\EasySwoole\EasySwoole\Core::getInstance()->initialize()->globalInitialize();
go(function () {
$mysqlConfig = new \EasySwoole\ORM\Db\Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
//獲取連接
$connection = new \EasySwoole\ORM\Db\Connection($mysqlConfig);
$tableName = 'user_list';
//獲取數據表結構對象
$tableObjectGeneration = new \EasySwoole\ORM\Utility\TableObjectGeneration($connection, $tableName);
$schemaInfo = $tableObjectGeneration->generationTable();
$path = "UnitTest";
$modelClass = \App\Model\UserModel::class;
$controllerClass= \App\HttpController\User::class;
$extendClass = \PHPUnit\Framework\TestCase::class;
$tablePre = '';//表前綴
$controllerConfig = new \EasySwoole\CodeGeneration\UnitTest\UnitTestConfig($modelClass, $controllerClass, $schemaInfo, $tablePre, "{$path}", $extendClass);
$controllerConfig->setRootPath(EASYSWOOLE_ROOT);
$unitTestGeneration = new \EasySwoole\CodeGeneration\UnitTest\UnitTestGeneration($controllerConfig);
$result = $unitTestGeneration->generate();
var_dump($result);
});
\Swoole\Timer::clearAll();
UnitTest方法.
UnitTest支持了5個方法,Add
,Delete
,GetList
,GetOne
,Update
.
自定義其他方法可參考Model方法自定義.
初始化類
為了方便開發,提供了Controller,Model,UnitTest的初始化類.
Controller
生成方法:
<?php
$generation = new \EasySwoole\CodeGeneration\InitBaseClass\Controller\ControllerGeneration();
$generation->generate();
類內容:
<?php
namespace App\HttpController;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Trigger;
use EasySwoole\HttpAnnotation\AnnotationController;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
use EasySwoole\Http\Message\Status;
/**
* Base
* Class Base
* Create With ClassGeneration
*/
class Base extends AnnotationController
{
public function index()
{
$this->actionNotFound('index');
}
public function clientRealIP($headerName = 'x-real-ip')
{
$server = ServerManager::getInstance()->getSwooleServer();
$client = $server->getClientInfo($this->request()->getSwooleRequest()->fd);
$clientAddress = $client['remote_ip'];
$xri = $this->request()->getHeader($headerName);
$xff = $this->request()->getHeader('x-forwarded-for');
if ($clientAddress === '127.0.0.1') {
if (!empty($xri)) { // 如果有xri 則判定為前端有NGINX等代理
$clientAddress = $xri[0];
} elseif (!empty($xff)) { // 如果不存在xri 則繼續判斷xff
$list = explode(',', $xff[0]);
if (isset($list[0])) $clientAddress = $list[0];
}
}
return $clientAddress;
}
public function onException(\Throwable $throwable): void
{
if ($throwable instanceof ParamValidateError) {
$this->writeJson(Status::CODE_BAD_REQUEST,[], $throwable->getValidate()->getError()->__toString());
} else {
Trigger::getInstance()->throwable($throwable);
$this->writeJson(Status::CODE_INTERNAL_SERVER_ERROR, null, $throwable->getMessage());
}
}
}
Model
生成方法:
<?php
$generation = new \EasySwoole\CodeGeneration\InitBaseClass\Model\ModelGeneration();
$generation->generate();
類內容:
<?php
namespace App\Model;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\DbManager;
/**
* BaseModel
* Class BaseModel
* Create With ClassGeneration
*/
class BaseModel extends AbstractModel
{
public static function transaction(callable $callable)
{
try {
DbManager::getInstance()->startTransaction();
$result = $callable();
DbManager::getInstance()->commit();
return $result;
} catch (\Throwable $throwable) {
DbManager::getInstance()->rollback();
throw $throwable;;
}
}
}
UnitTest
生成方法:
<?php
$generation = new \EasySwoole\CodeGeneration\InitBaseClass\UnitTest\UnitTestGeneration();
$generation->generate();
類內容:
<?php
namespace UnitTest;
use Curl\Curl;
use EasySwoole\EasySwoole\Core;
use PHPUnit\Framework\TestCase;
/**
* BaseTest
* Class BaseTest
* Create With ClassGeneration
*/
class BaseTest extends TestCase
{
public static $isInit = 0;
/** @var Curl */
public $curl;
public $apiBase = 'http://127.0.0.1:9501';
public $modelName;
public function request($action, $data = [], $modelName = null)
{
$modelName = $modelName ?? $this->modelName;
$url = $this->apiBase . '/' . $modelName . '/' . $action;
$curl = $this->curl;
$curl->post($url, $data);
if ($curl->response) {
// var_dump($curl->response);
} else {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "
";
}
$this->assertTrue(!!$curl->response);
$this->assertEquals(200, $curl->response->code, $curl->response->msg);
return $curl->response;
}
public function setUp()
{
if (self::$isInit == 1) {
return true;
}
require_once dirname(__FILE__, 2) . '/vendor/autoload.php';
defined('EASYSWOOLE_ROOT') or define('EASYSWOOLE_ROOT', dirname(__FILE__, 2));
require_once dirname(__FILE__, 2) . '/EasySwooleEvent.php';
Core::getInstance()->initialize()->globalInitialize();
self::$isInit = 1;
$this->curl = new Curl();
}
}