PHPackages                             hwalde/database2code - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. hwalde/database2code

ActiveLibrary[Database &amp; ORM](/categories/database)

hwalde/database2code
====================

v0.11.0-beta(7y ago)0321BSD-3-ClausePHPPHP ^7.0

Since Jul 1Pushed 3y agoCompare

[ Source](https://github.com/hwalde/database2code)[ Packagist](https://packagist.org/packages/hwalde/database2code)[ RSS](/packages/hwalde-database2code/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (2)Dependencies (2)Versions (4)Used By (1)

Database2Code
=============

[](#database2code)

Database2Code is a tool to dump the structure of your database, or single tables into sourcecode (e.g. PHP) files or potential other formats.

It is the PHP equivalent to the code generator from jOOQ.

Purpose
-------

[](#purpose)

Do you want auto-completion on table and column names? Like in the following PHP example:

```
$sql = 'SELECT '.s_core_engine_groups::variantable.' FROM '.s_core_engine_groups::class;
```

Then you need a tool to dump you database structure into php code.

This tool will do that for you!

You can use it either as command line program or use the PHP API.

Installation
------------

[](#installation)

### Installation PHP Archive (PHAR)

[](#installation-php-archive-phar)

We distribute a [PHP Archive (PHAR)](https://php.net/phar) file.

You can download and use the database2code.phar file [here](https://github.com/hwalde/database2code/releases).

```
$ php database2code.phar --help
```

### Using Composer

[](#using-composer)

Alternatively, you may use [Composer](https://getcomposer.org/) to download and install Database2Code.

```
$ composer require hwalde/database2code
```

Usage
-----

[](#usage)

### Usage from command line

[](#usage-from-command-line)

Convert all tables of a database:

```
$ php database2code \
    --dbms='mysql' \
    --mysql-host='localhost' \
    --mysql-user='username' \
    --mysql-password='password' \
    'pathToOutputFolder' 'database_name'
```

Convert only one table:

```
$ php database2code \
    --dbms='mysql' \
    --mysql-host='localhost' \
    --mysql-user='username' \
    --mysql-password='password' \
    'pathToOutputFolder' 'database_name' 'table_name'
```

#### Options

[](#options)

`--mysql-port [3306]` MySQL port

`--customTemplate [filePath]` Use a custom output-file template

`--customOutputFileGateway [FQN]` Use can specify a custom output-file generator

`--xml-config-file [filePath]` Read database config from an xml file

`--output-phpversion [version]` PHP version the code will be created for. Used in some output-templates. (Default: version of the executing interpreter)

`--output-namespace [namespace]` Namespace information. Used in some output-templates.

#### XML database configuration

[](#xml-database-configuration)

Instead of using the command line options to set database entries you can read them from an xml file instead. Simply use the "--xml-config-file" to set the filepath to the xml file.

Fileformat:

```

    mysql
    hostname
    the-username
    the-password
    3306

```

The port is optional! The Fileformat may vary depending on the type.

### Using the PHP API

[](#using-the-php-api)

```
$outputConfig = new \Database2Code\Output\OutputConfig();

// Optionally set your own (or some provided) template:
$outputConfig->setCustomTemplatePath('Template/PHPFile/getterAndSetter.php');

// And in case an own template is not enough customization, then you can provide an your own output-class.
// Note: Your output-class needs to implement \Database2Code\Output\Output interface.
// The required argument is the fully qualified classname to your output-class:
$outputConfig->setCustomOutputClassname(MyOutputOutput::class);

$output = new \Database2Code\Output\OutputConfig($outputConfig);
$service = new \Database2Code\Service\ConvertService($output);

$inputConfig = new \Database2Code\Input\MySQL\MySQLInputConfig('username', 'password', 'hostname');

// Convert entire database:
$service->convertDatabase($inputConfig, 'database-name', 'output/folder/path');

// Convert single table:
$service->convertTable($inputConfig, 'database-name', 'table-name', 'output/folder/path');
```

Extending and Customizing
-------------------------

[](#extending-and-customizing)

### Adding another DBMS

[](#adding-another-dbms)

Currently only MySQL is implemented. But adding other DBMS types (SQLite, Oracle, ...) is easy.

All you have to do is (lets assume we want to add PostgreSQL):

1. Create a class that will contain the connection information `Input/PostgreSQL/PostgreSQLInputConfig.php` that implements `Input/InputConfig`. Since in this case it is PostgreSQL you ca probably copy 99% from `MySQLInputConfig.php`
2. Create a `Input/PostgreSQL/PostgreSQLInput.php` class that implements `DBMSGatewayInterface`.
3. Add the new DBMS to `Service/ConvertService.php`: ```
    use Database2Code\Input\PostgreSQL\PostgreSQLInputConfig;
    use Database2Code\Input\PostgreSQL\PostgreSQLInput;

    private function generateInputInstance(InputConfig $inputConfig, string $database) : Input
    {
        if ($inputConfig instanceof MySQLInputConfig) {
            return new MySQLInput($inputConfig, $database, new MySQLTableHydrator());
        }
        if ($inputConfig instanceof PostgreSQLInputConfig) {
            return new PostgreSQLGateway($inputConfig);
        }
        throw new \Error('Unknown InputConfig "' . get_class($dbConfig) . '"!');
    }
    ```
4. Add it to `Console/Application.php`
5. Create a pull request on Github

Appendix
--------

[](#appendix)

### More on the purpose of this tool

[](#more-on-the-purpose-of-this-tool)

##### This is useful combined with an Database-API:

[](#this-is-useful-combined-with-an-database-api)

When you already use auto-completion while use an api to access your database, then you will find it comfortable doing that with the table and column names as well:

```
$rows = $db->select('*')
    ->from(s_core_engine_groups::class)
    ->whereIsTrue(s_core_engine_groups::variantable)
    ->fetchAll();

foreach($rows as $row) {
    echo $row[s_core_engine_groups::name];
}
```

##### What if names change?

[](#what-if-names-change)

Now imagine you want to change the column name "variantable" to something else. Usually that would mean changing it in the database and than rewriting all the sourcefiles of your project where that name is used. Hoping that you don't miss out some part. Or alternatively using Search&amp;Replace. But with general purpose names this only leads to disaster.

This doesn't have to be!

Using objects instead of strings..

1. you have successfully decoupled your codebase from the actual name in your database and change the used name by changing the model instead of you codebase. (Change one file instead of numerous ones.)
2. you can use the Refactor-&gt;Rename feature of your IDE to make your code look pretty again. You can easily improve readability whenever you like. Whenever you want to know the actuall name of a column you can always hover it with your cursor. You IDE then will display it to you.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~129 days

Total

3

Last Release

2616d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/add9f890078f12af912417780d3633d1c66b621c198cd33c68d3593938df2f6c?d=identicon)[hwalde](/maintainers/hwalde)

---

Top Contributors

[![hwalde](https://avatars.githubusercontent.com/u/40671872?v=4)](https://github.com/hwalde "hwalde (15 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hwalde-database2code/health.svg)

```
[![Health](https://phpackages.com/badges/hwalde-database2code/health.svg)](https://phpackages.com/packages/hwalde-database2code)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
