PHP code example of hnrazevedo / datamanager

1. Go to this page and download the library: Download hnrazevedo/datamanager library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hnrazevedo / datamanager example snippets


use HnrAzevedo\Datamanager\DatamanagerException;

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"
]);

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');
    }
}

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','[email protected]']
])->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();

$entity = new User();

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

/* Change info to update */
$user->name = 'Other Name';
$user->email = '[email protected]';

/* 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();

use Model\User;

$entity = new User();

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

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

use Model\User;

$entity = new User();

/* Set new info for insert in database */
$entity->name = 'Henri Azevedo';
$entity->email = '[email protected]';
$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();

use Model\User;

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

$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"
 *   }
 * }
 * 
*/

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;
    }

}