PHPackages                             hnrazevedo/datamanager - 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. hnrazevedo/datamanager

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

hnrazevedo/datamanager
======================

Datamanager is a simple persistence abstraction component in the database.

v2.1.4(5y ago)0280MITPHPPHP &gt;=7.4

Since Aug 11Pushed 4y ago1 watchersCompare

[ Source](https://github.com/hnrazevedo/Datamanager)[ Packagist](https://packagist.org/packages/hnrazevedo/datamanager)[ RSS](/packages/hnrazevedo-datamanager/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)DependenciesVersions (39)Used By (0)

Datamanager @HnrAzevedo
=======================

[](#datamanager-hnrazevedo)

[![Maintainer](https://camo.githubusercontent.com/635097b3bfe7b55e89a425855fb0567f79aea687d3f7176a187b388ed7c99d56/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d61696e7461696e65722d40686e72617a657665646f2d626c75653f7374796c653d666c61742d737175617265)](https://github.com/hnrazevedo)[![Latest Version](https://camo.githubusercontent.com/b561b88560a4c3e2cc62705d4477d080008e1ae82ea4d40ef4f9a88d5456b349/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f7461672f686e72617a657665646f2f446174616d616e616765723f6c6162656c3d76657273696f6e267374796c653d666c61742d737175617265)](https://github.com/hnrazevedo/Datamanager/releases)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/2b9bd0450b3938d5c764392fb225aa6f25c03c904272c737715d3cc805aa9769/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f686e72617a657665646f2f446174616d616e616765723f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/hnrazevedo/Datamanager/?branch=master)[![Build Status](https://camo.githubusercontent.com/fdf6e871bcabf59fa4a3bd78a0ccc226e497670b911d93c7028424bfeeb6f320/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f6275696c642f672f686e72617a657665646f2f446174616d616e616765723f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/hnrazevedo/Datamanager/build-status/master)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![PHP from Packagist](https://camo.githubusercontent.com/653b5819fb62956421acc7c7728b5ec8a2c7c23eda883822adf6acc9a6b8d729/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f686e72617a657665646f2f446174616d616e616765723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hnrazevedo/Datamanager)[![Total Downloads](https://camo.githubusercontent.com/2bfbcd363b896e2b34fc886c7dd8cf6219876569044b2e27d0b413427b521d4b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686e72617a657665646f2f446174616d616e616765723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hnrazevedo/Datamanager)

##### Datamanager is a simple persistence abstraction component in the database. Its author is not a professional in the development area, just someone from the Technology area who is improving his knowledge.

[](#datamanager-is-a-simple-persistence-abstraction-component-in-the-database-its-author-is-not-a-professional-in-the-development-area-just-someone-from-the-technology-area-who-is-improving-his-knowledge)

O Datamanager é um simples componente de abstração de persistência no banco de dados. Seu autor não é profissional da área de desenvolvimento, apenas alguem da área de Tecnologia que está aperfeiçoando seus conhecimentos.

### Highlights

[](#highlights)

- Easy to set up (Fácil de configurar)
- Total CRUD asbtration (Asbtração total do CRUD)
- Create safe models (Crie de modelos seguros)
- Composer ready (Pronto para o composer)

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

[](#installation)

Datamanager is available via Composer:

```
"hnrazevedo/datamanager": "^2.1"
```

or run

```
composer require hnrazevedo/Datamanager
```

Documentation
-------------

[](#documentation)

##### For details on how to use the Datamanager, see the sample folder with details in the component directory

[](#for-details-on-how-to-use-the-datamanager-see-the-sample-folder-with-details-in-the-component-directory)

Para mais detalhes sobre como usar o Datamanager, veja a pasta de exemplos com detalhes no diretório do componente

### Errors

[](#errors)

#### In case of errors, Datamanager will throw a DatamanagerException, so it is necessary to import it into your class

[](#in-case-of-errors-datamanager-will-throw-a-datamanagerexception-so-it-is-necessary-to-import-it-into-your-class)

Em casos de erros, o Datamanager disparara uma DatamanagerException, então é necessário importar a mesma em sua classe.

```
use HnrAzevedo\Datamanager\DatamanagerException;
```

### Connection

[](#connection)

##### To begin using the Datamanager, you need to connect to the database (MariaDB / MySql). For more connections [PDO connections manual on PHP.net](https://www.php.net/manual/pt_BR/pdo.drivers.php)

[](#to-begin-using-the-datamanager-you-need-to-connect-to-the-database-mariadb--mysql-for-more-connections-pdo-connections-manual-on-phpnet)

Para começar a usar o Datamanager precisamos de uma conexão com o seu banco de dados. Para ver as conexões possíveis acesse o [manual de conexões do PDO em PHP.net](https://www.php.net/manual/pt_BR/pdo.drivers.php)

```
define("DATAMANAGER_CONFIG", [
    "driver" => "mysql",
    "host" => "localhost",
    "charset" => "utf8",
    "port" => 3306,
    "username" => "root",
    "password" => "",
    "database" => "",
    "timezone" => "America/Sao_Paulo",
    "options" => [
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
        PDO::ATTR_CASE => PDO::CASE_NATURAL,
        PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
    ],
    "dateformat" => "d/m/Y",
    "datetimeformat" => "d/m/Y H:i:s",
    "lang" => "pt_br"
]);
```

### Your model

[](#your-model)

#### The Datamanager is based on an MVC structure. Soon to consume it is necessary to create the model of your table and inherit the Datamanager\\Model.

[](#the-datamanager-is-based-on-an-mvc-structure-soon-to-consume-it-is-necessary-to-create-the-model-of-your-table-and-inherit-the-datamanagermodel)

O Datamanager é baseado em uma estrutura MVC. Logo para consumir é necessário criar o modelo de sua tabela e herdar o Datamanager\\Model.

```
namespace Model;

use HnrAzevedo\Datamanager\Model;

class User extends Model
{
    public function __construct()
    {
        /* To return something in place in the database table field in case of errors. */
        /* NOTE: its definition is optional. */
        $this->fields = [
            'email' => 'Email',
            'username' => 'Nome de usuário'
        ];

        /**
         * @param string Table name
         * @param string Primary key column
         */
        parent::create('user', 'id');
    }
}
```

Methods
-------

[](#methods)

### Find

[](#find)

```
use Model\User;

$entity = new User();

/* Find by primary key */
$user = $entity->find(1)->execute()->first()->toEntity();

/* Search only for columns defined in advance  */
$user = $entity->find(1)->only(['name','email'])->execute()->first();
$name = $user->name;
$email = $user->email;
/* OR */
$name = $entity->find()->only('name')->execute()->first()->name;

/* Search except for columns defined in advance  */
$user = $entity->find()->except(['name','email'])->execute()->first();
/* OR */
$user = $entity->find()->except('name')->execute()->first();

/* Limit example */
$users = $entity->find()->limit(5)->execute()->result();
/* Offset example */
$users = $entity->find()->limit(5)->offset(5)->execute()->result();

/* OrdeBy example */
$users = $entity->find()->orderBy('birth ASC')->execute()->result();
/* OR */
$users = $entity->find()->orderBy('birth','ASC')->execute()->result();

/* Between example */
$user = $entity->find()->between([
    'AND birth'=> ['01/01/1996','31/12/1996']
    ])->execute()->first();

/* Condition AND is default */
$user = $entity->find()->between([
    'birth'=> ['01/01/1996','31/12/1996']
    ])->execute()->first();

/* Clause IN */
$user = $entity->find()->where([
    'birth'=> ['01/01/1996','31/12/1996']
    ])->execute()->first();

/* Where example */
$user->find()->where([
    ['name','=','Henri Azevedo'],
    'OR' => ['email','LIKE','otheremail@gmail.com']
])->execute();

/* Searches through all records and returns a result array */
$results = $entity->find()->execute()->result();

/* Searches for all records and returns an array of Model\User objects */
$results = $entity->find()->execute()->toEntity();
```

### Save

[](#save)

```
$entity = new User();

$user = $entity->find()->execute()->first();

/* Change info to update */
$user->name = 'Other Name';
$user->email = 'otheremail@gmail.com';

/* Upload by primary key from the uploaded entity */
/* If the changed information is a primary key or a foreign key it will be ignored in the update */
/* NOTE: Must already have the Model returned from a query */
$user->save();
```

#### If there are no state changes to be saved, a DatamanagerException will be thrown.

[](#if-there-are-no-state-changes-to-be-saved-a-datamanagerexception-will-be-thrown)

Caso não haja mudanças de estado para serem salvas, será lançada uma DatamanagerException.

### Remove

[](#remove)

```
use Model\User;

$entity = new User();

/* Remove by cause *Where* */
$entity->remove()->where([
    ['name','=','Other Name'],
    'OR' => ['email','LIKE','otheremail@gmail.com']
])->execute();

/* Remove by primary key */
/* NOTE: Required to have already returned a query */
$entity->remove()->execute();
/* OR */
$entity->remove(true);
```

### Persist

[](#persist)

```
use Model\User;

$entity = new User();

/* Set new info for insert in database */
$entity->name = 'Henri Azevedo';
$entity->email = 'hnr.azevedo@gmail.com';
$entity->password = password_hash('123456' ,PASSWORD_DEFAULT);
$entity->birth = '28/09/1996';
$entity->register = date('Y-m-d H:i:s');

/* Insert entity in database */
$entity->persist();
```

### Count

[](#count)

```
use Model\User;

$entity = new User();
$registers = $entity->find()->only('id')->execute()->count();
```

### debug

[](#debug)

```
$entity = new User();

$user = $entity->find()->execute();

var_dump($user->debug());           // Return string replacing clause values
/*
 * Result:
 * string(110) " SELECT id,name,username,email,password,code,birth,register,lastaccess,status,type FROM user  WHERE   1 = '1' "
*/

var_dump($user->debug(true));       // Return array with executed string and field values ​​in separate index
/*
 * Result:
 * array(2) {
 * ["query"]=>
 *   string(112) " SELECT id,name,username,email,password,code,birth,register,lastaccess,status,type FROM user  WHERE   1 = :q_10 "
 * ["data"]=>
 *   array(1) {
 *     ["q_10"]=>
 *     string(1) "1"
 *   }
 * }
 *
*/
```

### Cache model

[](#cache-model)

#### To avoid abstracting the greatest amount of persistence errors in the database, Datamanager describes the model as soon as the instance is created, in a static way, so that at other times of the application if the same by instance, the query will not be made again.

[](#to-avoid-abstracting-the-greatest-amount-of-persistence-errors-in-the-database-datamanager-describes-the-model-as-soon-as-the-instance-is-created-in-a-static-way-so-that-at-other-times-of-the-application-if-the-same-by-instance-the-query-will-not-be-made-again)

Para evitar abstrair a maior quantidade de erros de persistencias no banco de dados, o Datamanager faz um describe do model assim que o instânciado, de uma forma estática, para que em outros momentos da aplicação se o mesmo for instânciado, a consulta não sejá feita novamente.

#### To improve it even more, but the performance of your application is possible to cache this structure query, below is an example below a simple cache in SESSION.

[](#to-improve-it-even-more-but-the-performance-of-your-application-is-possible-to-cache-this-structure-query-below-is-an-example-below-a-simple-cache-in-session)

Para melhorar ainda mas o desempenho de sua aplicação é possível cachear está consulta da estrutura, segue exemplo abaixo de um simples cache em SESSION.

```
namespace App\Model;

use HnrAzevedo\Datamanager\Model as Entity;

Class User extends Entity
{

    public function __construct(){

        $this->fields = [
            'email' => 'Email',
            'username' => 'Nome de usuário'
        ];

        if(!isset($_SESSION['cache']['datamanager'][get_class($this)])){
            parent::create('user','id');
            $_SESSION['cache']['datamanager'][get_class($this)] = serialize($this->clone());
        }

        $this->clone(unserialize($_SESSION['cache']['datamanager'][get_class($this)]));
        return $this;
    }

}
```

Support
-------

[](#support)

##### Security: If you discover any security related issues, please email  instead of using the issue tracker.

[](#security-if-you-discover-any-security-related-issues-please-email-hnrazevedogmailcom-instead-of-using-the-issue-tracker)

Se você descobrir algum problema relacionado à segurança, envie um e-mail para  em vez de usar o rastreador de problemas.

Credits
-------

[](#credits)

- [Henri Azevedo](https://github.com/hnrazevedo) (Developer)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/hnrazevedo/Datamanager/blob/master/LICENSE.md) for more information.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

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

Recently: every ~21 days

Total

37

Last Release

1908d ago

Major Versions

v1.1.3 → v2.0.02020-10-05

### Community

Maintainers

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

---

Top Contributors

[![hnrazevedo](https://avatars.githubusercontent.com/u/56831533?v=4)](https://github.com/hnrazevedo "hnrazevedo (90 commits)")

### Embed Badge

![Health badge](/badges/hnrazevedo-datamanager/health.svg)

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

###  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)
