PHPackages                             tomvlk/sweet-orm - 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. tomvlk/sweet-orm

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

tomvlk/sweet-orm
================

Simple ORM for PHP, using your already existing structure, no command line required!

1.1.0(9y ago)31.1k1MITPHPPHP &gt;=5.6.0CI failing

Since Jan 10Pushed 6y ago1 watchersCompare

[ Source](https://github.com/tomvlk/sweet-orm)[ Packagist](https://packagist.org/packages/tomvlk/sweet-orm)[ Docs](https://github.com/tomvlk/sweet-orm)[ RSS](/packages/tomvlk-sweet-orm/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (18)Used By (1)

SweetORM
========

[](#sweetorm)

[![Build Status](https://camo.githubusercontent.com/e5d27dff0c35b1cebf31fef0b8648d22ae8c7c5bac11252bddfc871520f74745/68747470733a2f2f7472617669732d63692e6f72672f746f6d766c6b2f73776565742d6f726d2e737667)](https://travis-ci.org/tomvlk/sweet-orm)[![Coverage Status](https://camo.githubusercontent.com/faa587cc7f8d0838bcf987fa7f2f8eb5b93e26c0fed4fa9a3f9a26592e7d07c5/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f746f6d766c6b2f73776565742d6f726d2f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://coveralls.io/github/tomvlk/sweet-orm?branch=master)[![Codacy Badge](https://camo.githubusercontent.com/14c2a15f057c913b3f730a7d0697d17b5dd73cdbdafb67a2a01a7190bbf57e7f/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f67726164652f6239306334323438353132333430383261343361306330633934646537393232)](https://www.codacy.com/app/tomvalk/sweet-orm)[![Codacy Badge](https://camo.githubusercontent.com/61c4f1b3daf61403e0d0841fe59c5301a117e6c60a006b0ee3cff43c1742b7ec/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f636f7665726167652f6239306334323438353132333430383261343361306330633934646537393232)](https://www.codacy.com/app/tomvalk/sweet-orm)[![Latest Stable Version](https://camo.githubusercontent.com/3e786a05a5b0514814a6bc1bb3b9396ba140426fe8735b3f60f62c51c6d58d35/68747470733a2f2f706f7365722e707567782e6f72672f746f6d766c6b2f73776565742d6f726d2f762f737461626c65)](https://packagist.org/packages/tomvlk/sweet-orm)[![Latest Unstable Version](https://camo.githubusercontent.com/e316d81a878f0ab0ed8313472bf95735c7fce737e7845cdc403afa0a8823eefa/68747470733a2f2f706f7365722e707567782e6f72672f746f6d766c6b2f73776565742d6f726d2f762f756e737461626c65)](https://packagist.org/packages/tomvlk/sweet-orm)[![License](https://camo.githubusercontent.com/be659ebae0e9201caa45add0f138b5a5c9398be0973f02d5b5c80c9d58f3eaad/68747470733a2f2f706f7365722e707567782e6f72672f746f6d766c6b2f73776565742d6f726d2f6c6963656e7365)](https://packagist.org/packages/tomvlk/sweet-orm)

Simple and PHP orm, without having to use command line generators and migrators, can work on your existing table structure.

Configure and connecting
------------------------

[](#configure-and-connecting)

To start using the SweetORM you need to configure it, the whole back runs on PDO and needs to have a connection or configuration.

##### Inject PDO Connection

[](#inject-pdo-connection)

Only if you already have a PDO connection ready to the targetted database you could inject it.

```
\SweetORM\ConnectionManager::injectConnection($pdo); // Where $pdo is an instance of PDO. Active connection!
```

##### Configuring for separate connection

[](#configuring-for-separate-connection)

When you don't have a PDO connection you need to setup the configuration of your database before touching any of the entities

```
\SweetORM\Configuration::set('database_driver',   'pdo_mysql');     // No other drivers support right now
\SweetORM\Configuration::set('database_host',     'localhost');
\SweetORM\Configuration::set('database_port',     3306);            // Optional, default 3306
\SweetORM\Configuration::set('database_db',       'sweet_test');
\SweetORM\Configuration::set('database_user',     'root');
\SweetORM\Configuration::set('database_password', '');
```

Defining Entities
-----------------

[](#defining-entities)

Entities are PHP class declarations made up on your database table structure. You need to extend the abstract Entity in SweetORM and use the Annotations available in SweetORM.

```
/**
 * @EntityClass
 * @Table(name="post")     id; // Output: 1
```

#### Find by Query (Query Builder)

[](#find-by-query-query-builder)

The ORM has a build-in query building option you could easy trigger with the static method find() on the Entity class

```
$categories = Category::find()->all();
// $categories is now an array with all the categories in your database, all returned as Entity instances.
```

More information about the Query Builder will be available at the section [Query Building](#query-builder).

Saving
------

[](#saving)

Saving to the database is easy. To create a new instance of a entity, just create a new Entity object like this:

#### Creating new Entity

[](#creating-new-entity)

```
$category = new Category();
```

Then set all the properties:

```
$category->name = "Samples";
$category->description = "Sample posts";
```

And finally to save:

```
$category->save(); // -> returns true or false, true on success, false on failure, will also throw exceptions.
```

#### Changing Entity

[](#changing-entity)

To change an existing or fetched entity, just change the property value and use `save()` again.

```
$category = Category::get(1);
$category->name = "Samples - Old";
$category->save(); // -> returns true or false.
```

#### Delete Entity

[](#delete-entity)

To delete the entity from the database use the method `delete()` on the entity.

```
$category = Category::get(1);

// Delete
$category->delete();
```

Query Builder
-------------

[](#query-builder)

For finding the entity you could use the Query Builder. This will interactively build a SQL Query without knowing the exact syntax for the database.

### Selecting Entity

[](#selecting-entity)

Selecting entity with several query builder operations:

```
$category = Category::find()->where('name', 'News')->one();
```

This is the same as the following query:

```
SELECT * FROM category WHERE name = 'News' LIMIT 1;
```

### Builder Methods

[](#builder-methods)

Methods to build your query:

```
$query = Category::find();

$query->select();
$query->select('id name'); // Only fetch id and name column (not property!).

$query->from('table'); // Select from table (not needed when using entity!)

$query->where('column', '=', 'value'); // Middle is optional, default '='.
$query->where(array('column' => 'value', 'column2' => array('=' => 'vallue2'))); // Complex where.

$query->limit(50); // Limit by 50 rows
$query->offset(10); // Offset by 10.

$query->all(); // Execute query, fetchAll.
$query->one(); // Execute query, fetch first row.

// Write,update,delete
$query->insert('table'); // Insert into table.
$query->into('table'); // optional!
$query->values(array('column' => 'value')); // Set insert data.
$query->apply(); // boolean

$query->update('table');
$query->set(array('column' => 'value')); // Set new data.
$query->where('id', 1);
$query->apply();

$query->delete('table');
$query->where('id', 1);
$query->apply();
```

Of course you can chain all operations on the query builder.

Validation and filling
----------------------

[](#validation-and-filling)

Validation against null and non-null, types and constraints (defined as annotations) could make using the ORM in REST environments way better.

### Define constraints

[](#define-constraints)

```
class Test extends Entity {
    /**
     * @var string
     * @Column(type="string", null=true)
     * @Constraint(
     *     startsWith="www.",            'www.verylongurlthatvalidatescorrectly.com'
    );
    $result = Test::validator($data)->test();

    $result->isSuccess(); // true
    $result->getErrors(); // empty array.
```

### Filling and creating entities with raw data

[](#filling-and-creating-entities-with-raw-data)

Creating from the validator:

```
    // We are going to use the ArrayValidator (will be selected automatically)
    $data = array(
        'longUrl' => 'www.verylongurlthatvalidatescorrectly.com'
    );
    $entity = Test::validator($data)->create(); // Entity = instance of Test.

    $entity->save(); // true
```

Update with data provided by the validator

```
    // We are going to use the ArrayValidator (will be selected automatically)
    $entity = Test::get(1); // Instance of already existing test entity.

    $data = array(
        'longUrl' => 'www.verylongurlthatvalidatescorrectly2.com'
    );
    Test::validator($data)->fill($entity); // Entity = instance of Test.

    $entity->save(); // true, is now updated!
```

*Remember, by default the primary key(s) can't be overwritten by validator data!*

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity67

Established project with proven stability

 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 ~98 days

Recently: every ~346 days

Total

17

Last Release

2193d ago

Major Versions

0.9.0 → 1.0.02016-10-19

1.1.0 → 2.0.0-rc.12017-07-03

PHP version history (3 changes)0.1.0PHP &gt;=5.6.0

2.0.0-rc.1PHP &gt;=7.0.0

2.0.0-rc.2PHP &gt;=7.1.0

### Community

Maintainers

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

---

Top Contributors

[![tomvlk](https://avatars.githubusercontent.com/u/3877688?v=4)](https://github.com/tomvlk "tomvlk (122 commits)")

---

Tags

databaseormentityobjects

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tomvlk-sweet-orm/health.svg)

```
[![Health](https://phpackages.com/badges/tomvlk-sweet-orm/health.svg)](https://phpackages.com/packages/tomvlk-sweet-orm)
```

###  Alternatives

[vlucas/spot2

Simple DataMapper built on top of Doctrine DBAL

605392.8k7](/packages/vlucas-spot2)[ergebnis/factory-bot

Provides a fixture factory for doctrine/orm entities.

81702.8k](/packages/ergebnis-factory-bot)[liqueurdetoile/cakephp-orm-json

Cakephp plugin to provide easy control over JSON type fields in database

1461.1k](/packages/liqueurdetoile-cakephp-orm-json)[williarin/wordpress-interop

Interoperability library to work with WordPress database in third party apps

6610.9k2](/packages/williarin-wordpress-interop)[andsalves/doctrine-elastic

Elasticsearch Doctrine Adaptation

156.6k](/packages/andsalves-doctrine-elastic)

PHPackages © 2026

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