Resolving a Collision

  • A macro on the base Grammar class, combined with reflection, identifies the correct child class
  • This approach avoids overriding the class while still customising behaviour per database driver
Grammar::macro('typeEfficientUuid', function (Fluent $column) {
    $className = (new \ReflectionClass($this))->getShortName();

    if ($className === "MySqlGrammar") {
        return sprintf('binary(%d)', $column->length ?? 16);
    }

    if ($className === "PostgresGrammar") {
        return 'bytea';
    }

    if ($className === "SQLiteGrammar") {
        return 'blob(256)';
    }

    throw new UnknownGrammarClass();
});

← / → navigate · N notes · Esc exit