PHPackages                             gyde/mysql-object-model - 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. gyde/mysql-object-model

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

gyde/mysql-object-model
=======================

PHP ORM

v1.0.10(1y ago)24961[18 issues](https://github.com/gyde/MySQL-Object-Model/issues)[1 PRs](https://github.com/gyde/MySQL-Object-Model/pulls)MITPHPPHP ^7.4.0 || ^8.0.0

Since Feb 16Pushed 1y ago2 watchersCompare

[ Source](https://github.com/gyde/MySQL-Object-Model)[ Packagist](https://packagist.org/packages/gyde/mysql-object-model)[ Docs](https://github.com/gyde/MySQL-Object-Model)[ RSS](/packages/gyde-mysql-object-model/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (14)Used By (0)

MySQL-Obejct-Model
==================

[](#mysql-obejct-model)

A PHP Object Model using MySQL as backend via PDO. Allows fast scaffoling of Models with a high performance MySQL specific backend. First version is available, then more information regarding installation, use and namespacing will follow. Memcache and Static cache has been added for MOMBase and MOMSimple

Table of Contents
=================

[](#table-of-contents)

1. [Version](##Version)
2. [Usage](##Usage)
3. [Classes](##Classes)
4. [Caveats](##Cateats)
5. [Tools](#Tools)

Version
-------

[](#version)

This version is considered stable and will be version tagged 1.0 once its been field tested with php7.3!

Current projects using this project:

- Solaris - mobilspejd.dk - Scout race navigation system)
- DOG - roskilde-festival IT deployment tool
- Intranet - Ordbogen A/S intranet

No guareentes are given when using this code, but all suggestions and bugreports are welcome.

Usage
-----

[](#usage)

### Example table

[](#example-table)

```
CREATE TABLE `admin`.`userstest` (
	`user_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
	`active` BOOLEAN UNSIGNED NOT NULL DEFAULT TRUE,
	`created` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	PRIMARY KEY (`user_id`), INDEX (`name`))
	ENGINE = INNODB;
```

### Class definition

[](#class-definition)

A simple example on the usage of MOMSimple

```
class User extends \namespace\MOMSimple
{
	const DB = 'administration';
	const TABLE = 'users';

	// Primary column name (required)
	const COLUMN_PRIMARY_KEY = 'user_id';

	// Other column names (optional)
	const COLUMN_NAME = 'name';
	const COLUMN_ACTIVE = 'active';
	const COLUMN_CREATED = 'created';
}
```

You only need to define the optional columns you want to use for easy (constant safe) access, object member variables will be created from database table definition using SQL lookup.

### Connecting SQL using PDO

[](#connecting-sql-using-pdo)

```
$connection = new \PDO('mysql:host=127.0.0.1', 'myuser', 'mypasswd');

// Sets a global PDO connection for MOMBase to use
\namespace\MOMBase::setConnection($connection, TRUE);

// Sets a specific PDO connection for User to use
User::setConnection($connection);
```

### Creating and saving objects

[](#creating-and-saving-objects)

```
// Create a new object
$object1 = new User();

// Set object properties (all properties are public by default)
$object1->name = 'foo';
$object1->description = 'imfulloffoo';

// Save the object to the database and refetch it (update autoincrements, timestamps and other default values
$object1->save();
```

#### Get object by primary key

[](#get-object-by-primary-key)

```
// Fetch the object we just created using primary id (assuming user_id is 1)
$object1 = User::getById(1);
if ($object1 instanceOf User)
{
	echo $object1->name;
}
```

### Fetching objects

[](#fetching-objects)

#### All

[](#all)

```
// Fetch all User objects
$users = User::getAll();
foreach ($users as $user)
{
	echo $user->name;
}
```

#### Filtering

[](#filtering)

A small guide to filtering using where clauses on many or one object

##### Many

[](#many)

Fetch some User objects by SQL where clause

```
$where = '`'.User::COLUMN_NAME.'` = '.User::escapeStatic('foo');
$someObjects = User::getAllByWhere($where);
foreach ($someObjects as $object)
{
	echo $object->name;
```

Functionality like the above example should in general be placed inside the object class like so:

```
class User extends MOMSimple
{
	...
	/**
	  * Fetch users using name
	  * @param string $name
	  * @return array
	  */
	public static function getByName($name)
	{
		$where = '`'.self::COLUMN_NAME.'` = '.self::escapeStatic($name);
		return self::getAllByWhere($where, null, true);
	}
	...
}
```

##### One

[](#one)

Fetch one User object by SQL where clause

```
$where = '`'.User::COLUMN_NAME.'` = '.User::escapeStatic('foo');
$order = '`'
$someObjects = User::getOne($where);
foreach ($someObjects as $object)
{
	echo $object->name;
}
```

### Modifying object

[](#modifying-object)

#### When fetching objects

[](#when-fetching-objects)

You can overwrite the default load method to change member variables after an object is fetched from the database, you might want to "cast" all timestamps and datetimes into DateTime objects

```
class User extends MOMSimple
{
	...
	/**
	  * Fills object
	  * Creates public vars on object with name of row key, and value of row value
	  * Sets object to be old, meaning that its been fetched from database
	  * @param string[] $row \PDO_result->fetch_assoc
	  */
	protected function fill($row)
	{
		parent::fill($row);

		$this->created = DateTime::createFromFormat('Y-m-d H:i:s', $this->created);
	}
	...
}

```

Classes / Types
---------------

[](#classes--types)

### MOMBase.class.php

[](#mombaseclassphp)

The generic / factory class which all object models extends from. This contains generic query function and requires that extending classes implements needed methods.

### MOMSimple.class.php

[](#momsimpleclassphp)

A simple scaffoling class for MySQL tables with ONE column as primary key

### MOMCompound

[](#momcompound)

A compound scaffoling class for MySQL tables with SEVERAL columns as primary key

Caveats
-------

[](#caveats)

Here is a list of common tips, tricks and caveats currently in the MOM system.

### On update / default value columns

[](#on-update--default-value-columns)

If you create a table with a column that has a default "current timestamp" value or "on update" property beware that this column is controlled completely by MOM and can't be updated by setting a value on public class variable. The column is omitted from any insert or update statements that MOM performs.

Tests (PHPUnit)
---------------

[](#tests-phpunit)

Tests has been designed using PHPUnit and will create and droppe tables as needed within the docker env. In order to run the tests, the following needs to be satisfied:

- A running docker-ce environment

Build the docker environment using ./docker/build\_container ./docker/bootstrap\_container /absolute/path/to/MySQL-Object-Model/

Run ./run\_tests to start the tests within the docker env. ./run\_tests

### build\_mom

[](#build_mom)

Shell script to "build" MOM using first provided argument as namespace.

```
./build_mom my\\\\name\\\\space
```

MOM files will be placed in a folder called build with namespace my\\name\\space. Additional slashes are needed due to shell escaping

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance24

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 74% 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 ~74 days

Recently: every ~117 days

Total

11

Last Release

435d ago

### Community

Maintainers

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

---

Top Contributors

[![gyde](https://avatars.githubusercontent.com/u/2420240?v=4)](https://github.com/gyde "gyde (94 commits)")[![Oinkling](https://avatars.githubusercontent.com/u/38097486?v=4)](https://github.com/Oinkling "Oinkling (31 commits)")[![CHH-Ordbogen](https://avatars.githubusercontent.com/u/140504556?v=4)](https://github.com/CHH-Ordbogen "CHH-Ordbogen (2 commits)")

---

Tags

databaseorm

### Embed Badge

![Health badge](/badges/gyde-mysql-object-model/health.svg)

```
[![Health](https://phpackages.com/badges/gyde-mysql-object-model/health.svg)](https://phpackages.com/packages/gyde-mysql-object-model)
```

###  Alternatives

[friendsofsymfony1/doctrine1

PHP Database ORM for Symfony1. Do NOT use for new projects: please move to a newest Symfony release and Doctrine2

40581.8k](/packages/friendsofsymfony1-doctrine1)[icanboogie/activerecord

ActiveRecord Object-relational mapping

135.0k3](/packages/icanboogie-activerecord)[andreagroferreira/laravel-sync-tracker

A Laravel package for tracking entity synchronization status between systems

113.0k](/packages/andreagroferreira-laravel-sync-tracker)

PHPackages © 2026

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