Examples
NexaModel documentation.
NexaModel · Storage() · NexaDb
$this->Storage('news')->where()->first();Complete CRUD Example
<?php
namespace App\Models;
use App\System\NexaModel;
class Article extends NexaModel
{
protected $table = 'articles';
public function createArticle(array $data): array
{
try s') ]); return [ 'success' => true, 'message' => 'Article created successfully', 'id' => $articleId ]; catch (\Exception $e) {
return [
'success' => false,
'message' => 'Error: ' . $e->getMessage()
];
}
}
public function getPublishedArticles(int $page = 1, int $perPage = 10): array
{
return $this->Storage($this->table)
->where('status', 'published')
->orderBy('created_at', 'DESC')
->paginate($page, $perPage);
}
public function searchArticles(string $keyword): array
{
return $this->Storage($this->table)
->where('title', 'LIKE', "%{$keyword}%")
->orWhere('content', 'LIKE', "%{$keyword}%")
->where('status', 'published')
->get();
}
public function getArticleStats(): array
{
return $this->Storage($this->table)
->countWithPercentage('status', ['published', 'draft', 'archived']);
}
}
Usage in Controller
<?php
namespace App\Controllers;
use App\Models\Article;
class ArticleController
{
private $articleModel;
public function __construct()
{
$this->articleModel = new Article();
}
public function index()
{
$page = $_GET['page'] ?? 1;
$articles = $this->articleModel->getPublishedArticles($page, 15);
// Return view with articles
return view('articles.index', compact('articles'));
}
public function store()
{
$result = $this->articleModel->createArticle($_POST);
if ($result['success']) {
redirect('/articles?success=1');
} else {
redirect('/articles/create?error=' . urlencode($result['message']));
}
}
public function search()
{
$keyword = $_GET['q'] ?? '';
$articles = $this->articleModel->searchArticles($keyword);
return json_encode($articles);
}
public function stats()
{
$stats = $this->articleModel->getArticleStats();
return json_encode($stats);
}
}
Generic Record Operations Example
<?php
namespace App\Controllers;
use App\System\NexaModel;
class UserController
{
private $model;
public function __construct()
{
$this->model = new NexaModel();
}
public function create()
{
try {
$userId = $this->model->insertRecord('users', [
'name' => $_POST['name'],
'email' => $_POST['email'],
'password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
'status' => 'active'
]);
return json_encode([
'success' => true,
'message' => 'User created successfully',
'id' => $userId
]);
} catch (\Exception $e) {
return json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}
}
public function update($id)
{
try 'User not found' ]); catch (\Exception $e) {
return json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}
}
public function delete($id)
{
try 'User not found' ]); catch (\Exception $e) {
return json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}
}
public function show($id)
{
try {
$user = $this->model->findRecord('users', $id);
if ($user) {
return json_encode([
'success' => true,
'data' => $user
]);
} else {
return json_encode([
'success' => false,
'message' => 'User not found'
]);
}
} catch (\Exception $e) {
return json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}
}
}
Advanced Statistics Example
<?php
namespace App\Models;
use App\System\NexaModel;
class Dashboard extends NexaModel
{
public function getUserStatistics(): array
{
// Multiple statistics dalam satu call
$stats = $this->Storage('users')
->countMultipleWhere([
'active_users' => [
['status', '=', 'active'],
['verified', '=', 1]
],
'inactive_users' => [
['status', '=', 'inactive']
],
'unverified_users' => [
['verified', '=', 0]
],
'admin_users' => [
['role', '=', 'admin']
]
]);
return $stats;
}
public function getOrderStatistics(): array
{
// Get order statistics dengan percentage
$orderStats = $this->Storage('orders')
->countWithPercentage('status', ['completed', 'pending', 'cancelled']);
// Get revenue statistics
$revenueStats = $this->Storage('orders')
->where('status', 'completed')
->sumColumnsWithPercentage(['total_amount', 'tax_amount', 'shipping_cost']);
return array_merge($orderStats, $revenueStats);
}
public function getQuickStats(): array
{
// Quick status count
$userStatus = $this->Storage('users')
->quickStatusCount('status', ['active', 'inactive', 'banned']);
$orderStatus = $this->Storage('orders')
->quickStatusCount('status', ['completed', 'pending', 'cancelled']);
return [
'users' => $userStatus,
'orders' => $orderStatus
];
}
public function displayDashboard(): void
{
// Display statistics dengan format yang rapi
echo "<h2>User Statistics</h2>";
$this->Storage('users')
->countByConditionsAndDisplay('status', [
'active' => ['status', '=', 'active'],
'inactive' => ['status', '=', 'inactive']
], true);
echo "<h2>Order Statistics</h2>";
$this->Storage('orders')
->countWithPercentageAndDisplay('status', ['completed', 'pending'], true);
echo "<h2>Revenue Statistics</h2>";
$this->Storage('orders')
->where('status', 'completed')
->aggregateAndDisplay(['total_amount', 'tax_amount'], 'sum', true);
}
/**
* Get safe user data for API (no sensitive fields)
*/
public function getSafeUserData()
{
return $this->Storage('users')
->noSensitive()
->onlyActive()
->orderBy('name')
->get();
}
/**
* Get financial accounts excluding salary data
*/
public function getPublicAccounts()
{
return $this->Storage('accounts')
->noSelectFields(['account_name' => ['Biaya Gaji', 'Biaya Rahasia']])
->onlyActive()
->orderBy('budget', 'DESC')
->get();
}
}
Debugging dan Development Tools
Query Debugging
// Lihat SQL query yang akan dieksekusi
$sql = $this->Storage('users')
->where('status', 'active')
->toSql();
echo $sql;
// Lihat bindings
$bindings = $this->Storage('users')
->where('status', 'active')
->getBindings();
print_r($bindings);
// Debug dump query dan stop execution
$this->Storage('users')
->where('status', 'active')
->dd();
// Dump query tanpa stop execution
$this->Storage('users')
->where('status', 'active')
->dump()
->get();
Performance Testing
// Test performa query
$benchmark = $this->Storage('users')
->where('status', 'active')
->benchmarkQuery(100); // 100 iterations
print_r($benchmark);
// Output: ['iterations' => 100, 'total_time' => 0.5, 'avg_time' => 0.005, ...]
Database Health Check
// Check database health
$health = $this->healthCheck();
print_r($health);
// Display health dengan format
$this->showHealth(true);
Column Validation Testing
// Test validasi kolom
$columns = [
'name',
'email',
'UPPER(name) AS name_upper',
'invalid_function()' // akan error
];
$validation = $this->testColumnValidation($columns);
print_r($validation);
// Display hasil validasi
$this->testColumnValidationAndDisplay($columns, true);
Lanjut
Topik sebelumnya: Advanced Features. Topik berikutnya: Best Practices. Lihat juga Models, Events, Helper & template, daftar dokumentasi.