PHP code example of nabysyphpapi / xnabysygs

1. Go to this page and download the library: Download nabysyphpapi/xnabysygs 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/ */

    

nabysyphpapi / xnabysygs example snippets



NAbySy\xNAbySyGS as N;

$nabysy = N::Init(
    "MonApp",              // Nom de l'application
    "Ma Société SARL",     // Nom du client
    "123 Rue Example",     // Adresse
    "+221 33 123 45 67",   // Téléphone
    "ma_base",             // Base de données
    "nabysygs",            // Base master
    "localhost",           // Serveur MySQL
    "root",                // Utilisateur
    "",                    // Mot de passe
    3306                   // Port
);

// Mode debug (développement uniquement)
N::SetShowDebug(true);

// Traiter les requêtes HTTP
N::ReadHttpRequest();


// ── categorie: client ──────────────────────────────── 2026-04-25 00:44 ──
N::$GSModManager::CreateCategorie("client", true, true, "clients");
// ── end: client ────────────────────────────────────────────────────────

// ── categorie: client_url ──────────────────────────── 2026-04-25 00:44 ──
N::$GSModManager::GenerateUrlRouteController("client", "client");
// ── end: client_url ────────────────────────────────────────────────────


use NAbySy\xNAbySyGS as N;

// Créer un module "client" avec action API et classe ORM
N::$GSModManager::CreateCategorie(
    "client",   // Nom du module
    true,       // Créer fichier action
    true,       // Créer classe ORM
    "clients"   // Nom de la table
);


use NAbySy\ORM\xORMHelper;

$nabysy = N::getInstance();

// Créer un client
$client            = new xORMHelper($nabysy, null, true, "clients");
$client->Nom       = "Dupont";
$client->Prenom    = "Jean";
$client->Email     = "[email protected]";
$client->Telephone = "771234567";
$client->Enregistrer();

echo "Client créé avec ID : " . $client->Id;

// Appel
GET /gs_api.php?action=CLIENT_LIST
POST /gs_api.php  { "action": "CLIENT_CREATE", "nom": "Dupont" }

// gs/client/client_action.php
switch ($action) {
    case 'CLIENT_LIST':
        $client = new xORMHelper($nabysy, null, true, "clients");
        echo $nabysy->SQLToJSON($client->ChargeListe());
        break;

    case 'CLIENT_CREATE':
        if (!$nabysy->ValideUser()) exit;
        $client      = new xORMHelper($nabysy, null, true, "clients");
        $client->Nom = $_REQUEST['nom'];
        $client->Enregistrer();
        break;
}

// db_structure.php
N::$GSModManager::GenerateUrlRouteController("client", "client");

// gs/client/ClientRouteController.php

$router->get('/clients', 'CLIENT_LIST');
$router->get('/clients/{id}', 'CLIENT_SHOW');
$router->post('/clients', 'CLIENT_CREATE');
$router->put('/clients/{id}', 'CLIENT_UPDATE');
$router->delete('/clients/{id}', 'CLIENT_DELETE');

// Avec contrainte sur le paramètre
$router->get('/clients/{id}', 'CLIENT_SHOW')->where('id', '[0-9]+');

// Route optionnelle
$router->get('/clients/{id?}', 'CLIENT_LIST_OR_SHOW');

// Groupe de routes avec préfixe
$router->prefix('/api/v1')->group(function($router) {
    $router->get('/clients', 'CLIENT_LIST');
    $router->get('/produits', 'PRODUIT_LIST');
});

// gs/client/client_action.php
case 'CLIENT_SHOW':
    $id     = $nabysy->RouteParam('id');
    $client = new xORMHelper($nabysy, $id, true, "clients");
    echo json_encode($client->ToObject());
    break;

// Appliquer un middleware sur une route spécifique
$router->get('/clients', 'CLIENT_LIST')->middleware('auth');

// Appliquer sur un groupe
$router->middleware('auth')->group(function($router) {
    $router->post('/clients', 'CLIENT_CREATE');
    $router->put('/clients/{id}', 'CLIENT_UPDATE');
    $router->delete('/clients/{id}', 'CLIENT_DELETE');
});

// Route publique (sans middleware)
$router->get('/clients/public', 'CLIENT_PUBLIC_LIST')->withoutMiddleware('auth');

$produit        = new xORMHelper($nabysy, null, true, "produits");
$produit->Nom   = "Laptop Dell";
$produit->Prix  = 550000;
$produit->Stock = 10;
$produit->Enregistrer();

// Par ID
$produit = new xORMHelper($nabysy, 5, true, "produits");
echo $produit->Nom;

// Liste avec critères
$liste = $produit->ChargeListe(
    "Prix > 100000 AND Stock > 0",  // Critère WHERE
    "Nom ASC",                       // ORDER BY
    "*",                             // SELECT
    null,                            // GROUP BY
    "10"                             // LIMIT
);

while ($row = $liste->fetch_assoc()) {
    echo $row['Nom'];
}

$produit       = new xORMHelper($nabysy, 5, true, "produits");
$produit->Prix = 500000;
$produit->Enregistrer();

$produit = new xORMHelper($nabysy, 5, true, "produits");
$produit->Supprimer();

$json  = $produit->ToJSON();
$obj   = $produit->ToObject();
$array = $produit->ToArrayAssoc();

$produitOriginal = new xORMHelper($nabysy, 5, true, "produits");

// Cloner dans la même base
$clone = $produitOriginal->Clone();

// Cloner vers une autre base
$clone = $produitOriginal->Clone("autre_base");

$nabysy = xNAbySyGS::getInstance();
$Pays   = new xPays($nabysy);
$Maison = new xMaison($nabysy);

$Rep     = new xNotification();
$Rep->OK = 1;

$Lst = $Maison
    ->JoinTable($Pays, null, "IdPays", "ID")  // Maison.IdPays = Pays.ID
    ->JointureChargeListe();                   // exécution de la requête jointe

$Rep->Contenue = $nabysy->SQLToJSON($Lst);
echo json_encode($Rep);

$liste = $Commande
    ->JoinTable($Client,   null, "IdClient",  "ID")
    ->JoinTable($Boutique, null, "IdBoutique", "ID")
    ->JointureChargeListe();

use NAbySy\xUser;
use NAbySy\xAuth;

$user = new xUser($nabysy, null, true, "utilisateur", $_REQUEST['Login']);

if ($user->CheckPassword($_REQUEST['Password'])) {
    $auth  = new xAuth($nabysy, 3600); // Token valide 1h
    $token = $auth->GetToken($user);

    echo json_encode([
        'OK'    => 1,
        'Token' => $token,
        'User'  => $user->ToObject()
    ]);
}

// Au début de votre action
if (!$nabysy->ValideUser()) {
    // Retourne automatiquement une erreur 401
    exit;
}

// Définir une session de 24h (86400 secondes)
N::SetAuthSessionTime(86400);

// Aucune configuration nécessaire !
$produit      = new xORMHelper($nabysy, null, true, "produits");
$produit->Nom = "Laptop";
$produit->Enregistrer(); // ✨ Déclenche automatiquement "xProduit_ADD"

// Eloquent nécessite de déclarer chaque Model
class Produit extends Model {
    protected static function boot() {
        parent::boot();
        static::created(function($produit) {
            // Configuration manuelle requise
        });
    }
}

// Un seul observateur pour plusieurs entités !
class xObservStock extends xObservGen {
    public function __construct($nabysy) {
        parent::__construct($nabysy, 'ObservStock', [
            'xProduit_EDIT',   // Observer les produits
            'xCommande_ADD',   // Observer les commandes
            'xVente_ADD',      // Observer les ventes
        ]);
    }

    public function RaiseEvent($ClassName, $EventType, &$EventArg) {
        switch ($EventType[0]) {
            case 'xProduit_EDIT':
                $this->checkStock($EventType[1]);
                break;
            case 'xCommande_ADD':
                $this->updateInventory($EventType[1]);
                break;
        }
    }
}

// Créer une nouvelle table à la volée
$nouvelleEntite         = new xORMHelper($nabysy, null, true, "ma_nouvelle_table");
$nouvelleEntite->Champ1 = "Valeur";
$nouvelleEntite->Enregistrer();
// ✨ Déclenche automatiquement "xMaNouvelleTable_ADD" !

// Vos observateurs existants l'attrapent sans modification de code

class xObservAudit extends xObservGen {
    public function __construct($nabysy) {
        parent::__construct($nabysy, 'AuditGlobal', [
            '*_ADD',   // Toutes les créations
            '*_EDIT',  // Toutes les modifications
            '*_DEL',   // Toutes les suppressions
        ]);
    }

    public function RaiseEvent($ClassName, $EventType, &$EventArg) {
        $audit              = new xORMHelper($this->Main, null, true, "audit_log");
        $audit->Table       = $ClassName;
        $audit->Action      = $EventType[0];
        $audit->IdRecord    = $EventType[1];
        $audit->Date        = date('Y-m-d H:i:s');
        $audit->Utilisateur = $this->Main->User->Login ?? 'SYSTEM';
        $audit->Enregistrer();
    }
}

public function RaiseEvent($ClassName, $EventType, &$EventArg) {
    $action = $EventType[0];  // Type d'événement
    $id     = $EventType[1];  // ID de l'enregistrement
    $objet  = $EventType[2];  // ✨ Objet complet avec toutes les données

    // Vous pouvez MODIFIER l'objet dans l'observateur !
    if ($objet->Prix < 0) {
        $objet->Prix = 0; // Correction automatique
    }

    // Enrichir automatiquement les données
    if (empty($objet->DateCreation)) {
        $objet->DateCreation = date('Y-m-d H:i:s');
    }
}


namespace NAbySy\OBSERVGEN;

use NAbySy\xNAbySyGS;

class xObservProduit extends xObservGen {

    public function __construct(xNAbySyGS $NabySyGS) {
        $listeObservable = [
            'xProduit_ADD',
            'xProduit_EDIT',
            'xProduit_DEL',
        ];

        parent::__construct($NabySyGS, 'ObservateurProduit', $listeObservable);
    }

    public function RaiseEvent($ClassName, $EventType, &$EventArg) {
        $action = $EventType[0] ?? null;

        switch ($action) {
            case 'xProduit_ADD':
                $this->onProduitCreated($EventType[1]);
                break;
            case 'xProduit_EDIT':
                $this->onProduitUpdated($EventType[1], $EventType[2] ?? null);
                break;
            case 'xProduit_DEL':
                $this->onProduitDeleted($EventType[1], $EventType[2] ?? null);
                break;
        }
    }

    private function onProduitCreated($idProduit) {
        $this->Main::$Log->Write("Nouveau produit créé : ID $idProduit");
        $this->Main->AddToJournal('SYSTEME', 0, 'PRODUIT_CREATED',
            "Nouveau produit ajouté avec ID: $idProduit");
    }

    private function onProduitUpdated($idProduit, $produit) {
        if (!$produit) return;
        $this->Main::$Log->Write("Produit modifié : {$produit->Nom} (ID: $idProduit)");

        if ($produit->Stock < 10) {
            $this->alertLowStock($produit);
        }

        $this->Main->AddToJournal('SYSTEME', 0, 'PRODUIT_UPDATED',
            "Produit {$produit->Nom} modifié");
    }

    private function onProduitDeleted($idProduit, $produit) {
        $this->Main::$Log->Write("Produit supprimé : ID $idProduit");
        $this->Main->AddToJournal('SYSTEME', 0, 'PRODUIT_DELETED',
            "Produit ID $idProduit supprimé");
    }

    private function alertLowStock($produit) {
        $message = "Alerte stock : {$produit->Nom} - Stock: {$produit->Stock}";
        $this->Main::$Log->Write($message);
        // $this->Main::$SMSEngine->EnvoieSMS('+221771234567', $message);
    }
}


namespace NAbySy\OBSERVGEN;

use NAbySy\xNAbySyGS;
use NAbySy\ORM\xORMHelper;

class xObservCommande extends xObservGen {

    public function __construct(xNAbySyGS $NabySyGS) {
        parent::__construct($NabySyGS, 'ObservateurCommande', [
            'xCommande_ADD',
            'xCommande_EDIT',
        ]);
    }

    public function RaiseEvent($ClassName, $EventType, &$EventArg) {
        $action     = $EventType[0];
        $idCommande = $EventType[1];
        $commande   = $EventType[2] ?? null;

        switch ($action) {
            case 'xCommande_ADD':
                $this->onNewOrder($idCommande);
                break;
            case 'xCommande_EDIT':
                $this->onOrderStatusChanged($commande);
                break;
        }
    }

    private function onNewOrder($idCommande) {
        $commande = new xORMHelper($this->Main, $idCommande, false, "commandes");
        $client   = new xORMHelper($this->Main, $commande->IdClient, false, "clients");

        // Notifier le client
        $message = "Bonjour {$client->Nom}, votre commande #{$commande->Id} a été enregistrée.";
        if ($this->Main::$SMSEngine) {
            $this->Main::$SMSEngine->EnvoieSMS($client->Telephone, $message);
        }

        $this->Main::$Log->Write("Notification client envoyée : Commande #{$commande->Id}");

        // Mettre à jour les statistiques
        $this->updateStats($commande);

        // Déclencher le workflow
        $this->triggerWorkflow($commande);
    }

    private function onOrderStatusChanged($commande) {
        if ($commande->Statut === 'Livrée') {
            $this->sendDeliveryConfirmation($commande);
            $this->requestReview($commande);
        }

        if ($commande->Statut === 'Annulée') {
            $this->restoreStock($commande);
        }
    }

    private function updateStats($commande) {
        $stats = new xORMHelper($this->Main, null, true, "statistiques_ventes");
        $today = date('Y-m-d');

        $existing = $stats->ChargeListe("Date = '$today'");
        if ($existing->num_rows > 0) {
            $row   = $existing->fetch_assoc();
            $stats = new xORMHelper($this->Main, $row['ID'], true, "statistiques_ventes");
            $stats->NombreCommandes += 1;
            $stats->MontantTotal    += $commande->MontantTotal;
        } else {
            $stats->Date            = $today;
            $stats->NombreCommandes = 1;
            $stats->MontantTotal    = $commande->MontantTotal;
        }
        $stats->Enregistrer();
    }

    private function triggerWorkflow($commande) {
        $tache               = new xORMHelper($this->Main, null, true, "taches");
        $tache->Titre        = "Préparer commande #{$commande->Id}";
        $tache->Type         = "Préparation";
        $tache->IdCommande   = $commande->Id;
        $tache->Statut       = "En attente";
        $tache->DateCreation = date('Y-m-d H:i:s');
        $tache->Enregistrer();
    }

    private function restoreStock($commande) {
        $lignes = new xORMHelper($this->Main, null, false, "ligne_commande");
        $liste  = $lignes->ChargeListe("IdCommande = {$commande->Id}");

        while ($ligne = $liste->fetch_assoc()) {
            $produit        = new xORMHelper($this->Main, $ligne['IdProduit'], false, "produits");
            $produit->Stock += $ligne['Quantite'];
            $produit->Enregistrer();
        }
        $this->Main::$Log->Write("Stock restauré pour commande annulée #{$commande->Id}");
    }
}

private function onProduitCreated($idProduit) {
    $produit  = new xORMHelper($this->Main, $idProduit, false, "produits");
    $curl     = $this->Main::$CURL;
    $response = $curl->Post('https://api-externe.com/products', [
        'nom'   => $produit->Nom,
        'prix'  => $produit->Prix,
        'stock' => $produit->Stock,
    ]);

    if ($response['success']) {
        $produit->IdExterne = $response['id'];
        $produit->Enregistrer();
    }
}

private function onProduitUpdated($produit) {
    if ($produit->Stock < 10) {
        $message = "ALERTE: Stock faible pour {$produit->Nom} (Stock: {$produit->Stock})";
        $this->Main::$SMSEngine->EnvoieSMS('+221771234567', $message);
        $this->Main::$Log->Write($message);
    }
}

private function onVenteCreated($idVente) {
    $vente    = new xORMHelper($this->Main, $idVente, false, "ventes");
    $stats    = new xORMHelper($this->Main, null, true, "stats_ventes");
    $today    = date('Y-m-d');
    $existing = $stats->ChargeListe("Date = '$today'");

    if ($existing->num_rows > 0) {
        $row   = $existing->fetch_assoc();
        $stats = new xORMHelper($this->Main, $row['ID'], true, "stats_ventes");
        $stats->NombreVentes += 1;
        $stats->MontantTotal += $vente->Montant;
    } else {
        $stats->Date         = $today;
        $stats->NombreVentes = 1;
        $stats->MontantTotal = $vente->Montant;
    }
    $stats->Enregistrer();
}

use NAbySy\xNAbySyGS;

class MaClasseMetier {
    private $nabysy;

    public function __construct(xNAbySyGS $nabysy) {
        $this->nabysy = $nabysy;
    }

    public function faireQuelqueChose() {
        // ... votre logique ...

        $this->nabysy::RaiseEvent('MaClasseMetier', [
            'MonEvenement_CUSTOM',
            123,
            'Information supplémentaire'
        ]);
    }
}

// Dans votre observateur
public function RaiseEvent($ClassName, $EventType, &$EventArg) {
    if (!$this->State()) return;
    // ... logique normale ...
}

$observateur->State(false); // Désactiver
$observateur->State(true);  // Activer

$nabysy->ActiveDebug = true;

public function RaiseEvent($ClassName, $EventType, &$EventArg) {
    if ($this->Main->ActiveDebug) {
        $this->Main::$Log->Write("Événement déclenché : " . json_encode($EventType));
    }
    // ... logique ...
}

use NAbySy\GS\Boutique\xBoutique;

$boutique = new xBoutique($nabysy, 1);
echo $boutique->Nom;
$liste = $boutique->getListeBoutique();

use NAbySy\GS\Stock\xProduit;

$produit              = new xProduit($nabysy, 10);
$produit->Designation = "Smartphone";
$produit->PrixVente   = 150000;
$produit->Enregistrer();

use NAbySy\GS\Facture\xVente;

$vente               = new xVente($nabysy);
$vente->IdClient     = 5;
$vente->MontantTotal = 500000;
$vente->Enregistrer();

// gs/produit/produit_action.php
use NAbySy\ORM\xORMHelper;
use NAbySy\xNotification;

switch ($action) {
    case 'PRODUIT_CREATE':
        if (!$nabysy->ValideUser()) exit;

        $produit        = new xORMHelper($nabysy, null, true, "produits");
        $produit->Nom   = $_REQUEST['nom'];
        $produit->Prix  = $_REQUEST['prix'];
        $produit->Stock = $_REQUEST['stock'] ?? 0;

        if ($produit->Enregistrer()) {
            $rep           = new xNotification();
            $rep->Contenue = $produit->ToObject();
            echo json_encode($rep);
        }
        break;

    case 'PRODUIT_SEARCH':
        $produit   = new xORMHelper($nabysy, null, true, "produits");
        $recherche = $_REQUEST['q'] ?? '';

        $liste = $produit->ChargeListe(
            "Nom LIKE '%$recherche%'",
            "Nom ASC", "*", null, "20"
        );
        echo $nabysy->SQLToJSON($liste);
        break;
}

$nabysy->ActiveDebug = true;
N::SetShowDebug(true, E_ALL);

N::$RequetteToIgnoreInLOG[] = 'SELECT';
N::$RequetteToIgnoreInLOG[] = 'UPDATE';

$nabysy = N::Init(
    "MonApp", "Ma Société", "Adresse", "Téléphone",
    "ma_base", "nabysygs", "localhost", "root", "", 3306,
    "mon-dossier"
);

// NAbySyGS — 4 lignes
$produit       = new xORMHelper($nabysy, null, true, "produits");
$produit->Nom  = "Laptop";
$produit->Prix = 550000;
$produit->Enregistrer();

// Doctrine — Configuration complexe nécessaire
// - Entities avec annotations / mapping XML/YAML
// - Configuration du EntityManager
// - Commandes doctrine:schema

$user->DateNaissance = '1990-01-01'; // Champ créé automatiquement en base !
$user->Enregistrer();

// NAbySyGS — aucune configuration préalable
$liste = $Maison->JoinTable($Pays, null, "IdPays", "ID")->JointureChargeListe();

// Eloquent — déclaration obligatoire dans le Model
class Maison extends Model {
    public function pays() { return $this->belongsTo(Pays::class, 'IdPays'); }
}

// Avant
$produits = Produit::where('prix', '>', 1000)->orderBy('nom')->limit(10)->get();

// Après
$produit  = new xORMHelper($nabysy, null, true, "produits");
$produits = $produit->ChargeListe("prix > 1000", "nom ASC", "*", null, "10");

// Avant
$produit = $entityManager->getRepository(Produit::class)->find(1);
$produit->setPrix(5000);
$entityManager->flush();

// Après
$produit       = new xORMHelper($nabysy, 1, true, "produits");
$produit->Prix = 5000;
$produit->Enregistrer();

votre-projet/
├── vendor/
│   └── nabysyphpapi/xnabysygs/
├── gs/                         # Modules personnalisés (créés automatiquement)
│   └── client/
│       ├── client_action.php   # Endpoints Action API
│       └── xClient/
│           └── xClient.class.php  # Classe ORM
├── appinfos.php                # Configuration (généré par setup.html)
├── db_structure.php            # Déclaration des modules et routes
├── .htaccess                   # Redirection API (créé automatiquement)
└── index.php                   # Point d'entrée
bash
# Créer un client
curl -X POST https://votre-domaine.com/gs_api.php \
  -H "Content-Type: application/json" \
  -d '{
    "action": "CLIENT_CREATE",
    "nom": "Dupont",
    "telephone": "771234567",
    "Token": "votre_token_jwt"
  }'