PHP code example of easyswoole / code-generation

1. Go to this page and download the library: Download easyswoole/code-generation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

easyswoole / code-generation example snippets



/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2020-05-20
 * Time: 10:26
 */

() {
    //生成基础类

    $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);
});



/**
 * 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());


$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();



/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2020-05-20
 * Time: 10:26
 */
 () {
    $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
});


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();
    $data = [
        'page'=>$page,
        'pageSize'=>$pageSize,
        'list'=>$list,
        'total'=>$total,
        'pageCount'=>ceil($total / $pageSize)
    ];
    return $data;
}


$modelGeneration = new \EasySwoole\CodeGeneration\ModelGeneration\ModelGeneration($modelConfig);
//注入GetList方法
$modelGeneration->addGenerationMethod(new \EasySwoole\CodeGeneration\ModelGeneration\Method\GetList($modelGeneration));


/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2020-05-20
 * Time: 10:26
 */
 () {
    $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);
});



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;
	}


	protected function setUp(): void
	{
		if (self::$isInit == 1) {
		    return;
		}
		


/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2020-05-20
 * Time: 10:26
 */
 () {
    $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);
});



$generation = new \EasySwoole\CodeGeneration\InitBaseClass\Controller\ControllerGeneration();
    $generation->generate();



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());
		}
	}
}



$generation = new \EasySwoole\CodeGeneration\InitBaseClass\Model\ModelGeneration();
$generation->generate();



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;;
		}
	}
}


$generation = new \EasySwoole\CodeGeneration\InitBaseClass\UnitTest\UnitTestGeneration();
$generation->generate();



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;
	}


	protected function setUp(): void
	{
		if (self::$isInit == 1) {
		    return;
		}
		
bash
php vendor/bin/code-generator
bash
php vendor/bin/code-generator init
bash
php vendor/bin/code-generator all
bash
$ php vendor/bin/code-generator all --tableName=test_a --modelPath=\\Api --controllerPath=\\Api --unitTestPath=\\Api
┌────────────┬────────────────────────────────────────────────────────────────────────────┐
│ className  │                                  filePath                                  │
├────────────┼────────────────────────────────────────────────────────────────────────────┤
│ Model      │ /Users/gaobinzhan/Documents/Git/Framework/App/Model/Api/TestAModel.php     │
├────────────┼────────────────────────────────────────────────────────────────────────────┤
│ Controller │ /Users/gaobinzhan/Documents/Git/Framework/App/HttpController/Api/TestA.php │
├────────────┼────────────────────────────────────────────────────────────────────────────┤
│ UnitTest   │ /Users/gaobinzhan/Documents/Git/Framework/UnitTest/Api/TestATest.php       │
└────────────┴────────────────────────────────────────────────────────────────────────────┘