宣告: 由於 第一次釋出md文件, 如文件中不足之處請多多包涵和指教. 並且目前只實現了mysql的表註釋
修改的完整程式碼
效果
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
SchemaExtends::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
//擴充套件的方法
$table->tableComment('使用者表');
});
}
- 重寫遷移的門面(Schema)
如果需要擴充套件其他資料支援的話, 去掉 MySqlConnection 或者 改成其他介面
class SchemaExtends extends Facade
{
/**
* Get a schema builder instance for a connection.
*
* @param string $name
* @return \Illuminate\Database\Schema\Builder
*/
public static function connection($name)
{
return static::getSchemaBuilder($name);
}
/**
* Get a schema builder instance for the default connection.
*
* @return \Illuminate\Database\Schema\Builder
*/
protected static function getFacadeAccessor()
{
return static::getSchemaBuilder();
}
/**
* Get a schema builder instance for the default connection.
*
* @param string|null $name
* @return \Illuminate\Database\Schema\Builder
*/
protected static function getSchemaBuilder(string $name = null): Builder
{
//獲取連線
$connection = static::$app['db']->connection($name);
//由於目前只實現mysql. 所以增加了限制
if ($connection instanceof MySqlConnection) {
//繼承並且增加新的方法
$grammar = $connection->withTablePrefix(new MySqlGrammar());
$connection->setSchemaGrammar($grammar);
}
//獲取構建器
return $connection->getSchemaBuilder();
}
}
- Blueprint 使用混入 (Macroable) 來新增對外的方法
這裡是如何擴充套件的後續再說明
use Closure;
class Blueprint
{
/**
* 新增設定表備註
*
* @return \Closure
*/
public function tableComment(): Closure
{
return function (string $comment) {
//新增新的命令
$this->addCommand('tableComment', compact('comment'));
};
}
}
註冊服務
/**
* Class MacroableServiceProvider
*
* @package LittleSuperman\Database\Providers
*/
class MacroableServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
* @throws \ReflectionException
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function boot(): void
{
//使用混入
BlueprintSupport::mixin($this->app->make(Blueprint::class));
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
- 擴充套件遷移語法(MySqlGrammar)
class MySqlGrammar extends SuperMySqlGrammar
{
/**
* 設定表備註
*
* @param Blueprint $blueprint
* @param Fluent $command
* @return string
*/
public function compileTableComment(Blueprint $blueprint, Fluent $command): string
{
return "alter table {$this->wrapTable($blueprint)} comment ' {$command->comment}'";
}
}
其他
相關後續說明 等有空在慢寫
本作品採用《CC 協議》,轉載必須註明作者和本文連結