Best Practices
NexaModel documentation.
NexaModel · Storage() · NexaDb
$this->Storage('news')->where()->first();1. Model Organization
<?php
namespace App\Models;
use App\System\NexaModel;
class User extends NexaModel
{
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
// Definisikan relasi dan method custom
public function getActiveUsers(): array
{
return $this->Storage($this->table)
->where('status', 'active')
->get();
}
public function findByEmail(string $email): ?array
{
return $this->Storage($this->table)
->where('email', $email)
->first();
}
}
2. Error Handling
public function createUser(array $data): array
{
try {
$userId = $this->Storage('users')->insert($data);
return [
'success' => true,
'message' => 'User created successfully',
'id' => $userId
];
} catch (\Exception $e) {
// Log error
error_log('User creation failed: ' . $e->getMessage());
return [
'success' => false,
'message' => 'Failed to create user'
];
}
}
3. Input Validation
public function updateUser(int $id, array $data): array
{
// Validate input
$allowedFields = ['name', 'email', 'phone'];
$updateData = array_intersect_key($data, array_flip($allowedFields));
if (empty($updateData)) {
return ['success' => false, 'message' => 'No valid fields to update'];
}
try 'User not found' ]; catch (\Exception $e) {
return ['success' => false, 'message' => 'Update failed'];
}
}
4. Performance Optimization
// Gunakan select untuk kolom yang diperlukan saja
$users = $this->Storage('users')
->select(['id', 'name', 'email'])
->where('status', 'active')
->get();
// Gunakan pagination untuk data besar
$users = $this->Storage('users')
->paginate(1, 50);
// Untuk data “sering dibaca”, kurangi beban dengan select kolom terbatas + index DB di sisi MySQL
$popularArticles = $this->Storage('articles')
->select(['id', 'title', 'views'])
->where('views', '>', 1000)
->limit(100)
->get();
5. Security Best Practices
// Selalu gunakan prepared statements (otomatis di NexaModel)
$user = $this->Storage('users')
->where('email', $userInput) // Aman dari SQL injection
->first();
// Validasi input sebelum digunakan
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email format');
}
// Gunakan whitelist untuk kolom yang diizinkan
$allowedColumns = ['name', 'email', 'phone'];
$selectColumns = array_intersect($requestedColumns, $allowedColumns);
Lanjut
Topik sebelumnya: Examples. Topik berikutnya: API Reference. Lihat juga Models, Events, Helper & template, daftar dokumentasi.