soar-php 是一個基於小米公司開源的 soar 開發的 PHP 擴展包,方便框架中 SQL 語句調優。
$ composer require guanguans/soar-php --dev
# macOS $ wget https://github.com/XiaoMi/soar/releases/download/0.11.0/soar.darwin-amd64 # linux $ wget https://github.com/XiaoMi/soar/releases/download/0.11.0/soar.linux-amd64 # windows $ wget https://github.com/XiaoMi/soar/releases/download/0.11.0/soar.windows-amd64 # 用其餘命令或下載器下載都可以
<?php require_once __DIR__.'/vendor/autoload.php'; use Guanguans\SoarPHP\Soar; $config = [ // 下載的 soar 的路徑 '-soar-path' => '/Users/yaozm/Documents/wwwroot/soar-php/soar.darwin-amd64', // 測試環境配置 '-test-dsn' => [ 'host' => '127.0.0.1', 'port' => '3306', 'dbname' => 'database', 'username' => 'root', 'password' => '123456', ], // 日誌輸出文件 '-log-output' => './soar.log', // 報告輸出格式: 默認 markdown [markdown, html, json] '-report-type' => 'html', ]; $soar = new Soar($config);
vendor
同級目錄下新建 .soar.dist
或者 .soar
,內容參考 .soar.example,例如:php
<?php return [ // 下載的 soar 的路徑 '-soar-path' => '/Users/yaozm/Documents/wwwroot/soar-php/soar.darwin-amd64', // 測試環境配置 '-test-dsn' => [ 'host' => '127.0.0.1', 'port' => '3306', 'dbname' => 'database', 'username' => 'root', 'password' => '123456', ], // 日誌輸出文件 '-log-output' => './soar.log', // 報告輸出格式: 默認 markdown [markdown, html, json] '-report-type' => 'html', ];
而後初始化html
<?php require_once __DIR__.'/vendor/autoload.php'; use Guanguans\SoarPHP\Soar; $soar = new Soar();
方法調用:linux
$sql ="SELECT * FROM `fa_user` `user` LEFT JOIN `fa_user_group` `group` ON `user`.`group_id`=`group`.`id`;"; echo $soar->score($sql);
輸出結果:laravel
方法調用:git
$sql = "SELECT * FROM `fa_auth_group_access` `aga` LEFT JOIN `fa_auth_group` `ag` ON `aga`.`group_id`=`ag`.`id`;"; // 輸出 html 格式 echo $soar->htmlExplain($sql); // 輸出 md 格式 echo $soar->mdExplain($sql); // 輸出 html 格式 echo $soar->explain($sql, 'html'); // 輸出 md 格式 echo $soar->explain($sql, 'md');
輸出結果:github
方法調用:web
$sql = 'selec * from fa_user'; echo $soar->syntaxCheck($sql);
輸出結果:sql
At SQL 1 : line 1 column 5 near "selec * from fa_user" (total length 20)
方法調用:shell
$sql = 'select * from fa_user where id=1'; echo $soar->fingerPrint($sql);
輸出結果:json
select * from fa_user where id = ?
方法調用:
$sql = 'select * from fa_user where id=1'; var_dump($soar->pretty($sql));
輸出結果:
SELECT * FROM fa_user WHERE id = 1;
方法調用:
echo $soar->md2html("## 這是一個測試");
輸出結果:
... <h2>這是一個測試</h2> ...
方法調用:
var_dump($soar->help());
輸出結果:
··· 'Usage of /Users/yaozm/Documents/wwwroot/soar-php/soar: -allow-charsets string AllowCharsets (default "utf8,utf8mb4") -allow-collates string AllowCollates -allow-drop-index AllowDropIndex, 容許輸出刪除重複索引的建議 -allow-engines string AllowEngines (default "innodb") -allow-online-as-test AllowOnlineAsTest, 容許線上環境也能夠看成測試環境 -blacklist string 指定 blacklist 配置文件的位置,文件中的 SQL 不會被評審。 ···
方法調用:
$command = "echo '## 這是另外一個測試' | /Users/yaozm/Documents/wwwroot/soar-php/soar.darwin-amd64 -report-type md2html"; echo $soar->exec($command);
輸出結果:
... <h2>這是另外一個測試</h2> ...