Development Practices

Naming Conventions

Consistent naming conventions are crucial for maintaining readability and collaboration in software projects. Following these guidelines will help you create code that is easier to understand, maintain, and extend.


Overview

As the saying goes, "There are only two hard things in Computer Science: cache invalidation and naming things." While we can't make naming easier, we can establish consistent patterns that improve code readability and reduce cognitive load when working on Laravel projects.

General Principles

Good names should be:

  • Descriptive - clearly communicate purpose and intent
  • Concise - as short as possible without sacrificing clarity
  • Consistent - follow established patterns throughout the project
  • Contextual - consider where and how the name will be used

Naming Standards by Category

Code Elements

ElementConventionExamples
VariablescamelCase$userId, $totalAmount, $isActive
Class propertiescamelCaseprivate $accessToken, protected $createdAt
Class methodscamelCasegetFullName(), calculateTotal(), featuredArticle()
Global helperssnake_caseformat_rupiah(), convert_date()
ClassesStudlyCase (nouns)User, PaymentGateway, UserProfile
InterfacesStudlyCase (adjectives)Authenticatable, Reportable
TraitsStudlyCase (adjectives)Notifiable, Searchable

Controllers

TypeConventionExamples
Resource controllersStudlyCase (noun + Controller)UserController, ProductController, BukuTamuController
Single action controllersStudlyCase (verb + Controller)ClearCacheController, LogoutController, DownloadLaporanHarianController

Files and Paths

TypeConventionExamples
View fileskebab-caseuser-profile.blade.php, laporan-harian.blade.php
Partial viewskebab-case with leading underscore_header.blade.php, _tabel-pegawai.blade.php
Config fileskebab-caseapp.php, dynamic-form.php
Config keyssnake_case'allowed_types' => ['text', 'textarea']

Routing

ElementConventionExamples
Route URLskebab-casehttps://example.com/laporan-harian
Route nameskebab-case with dot separating resource and actionlowongan-kerja.index, user.create
Route parameterscamelCase{userId}, {lowonganKerja}

Database

ElementConventionExamples
Table namessnake_case (plural nouns)users, blog_posts, order_items
Grouped tablesPrefixed snake_casemaster_provinsi, master_kabupaten
Pivot tablesSingular model names in alphabetical orderrole_user, permission_role
Column namessnake_casefirst_name, created_at, is_active
Primary keysidid
Foreign keysSingular model name with _id suffixuser_id, post_id

Commands and Jobs

ElementConventionExamples
Artisan commandskebab-casephp artisan generate-laporan
Command classesStudlyCaseGenerateLaporanCommand
JobsStudlyCase (verb)ProcessPayment, SendReminderEmails

Best Practices

Be Consistent

Consistency is more important than the specific convention chosen. If you're joining an existing project, follow its established conventions even if they differ from these guidelines.

Use Descriptive Names

Avoid abbreviations and single-letter variables except in very limited contexts (like loop counters). Names should be self-explanatory:

PHP
// Poor naming
$u = User::find(1);
$r = $u->roles;
$p = [];
foreach ($r as $i) {
$p[] = $i->permissions;
}
// Better naming
$user = User::find(1);
$roles = $user->roles;
$permissions = [];
foreach ($roles as $role) {
$permissions[] = $role->permissions;
}

Consider Search-ability

Names should be distinct enough to allow for effective code searching:

PHP
// Hard to search for
$data = User::all();
// Better - unique and searchable
$activeUsers = User::where('status', 'active')->get();

Use Domain Language

Align your naming with the domain language of your project:

PHP
// Generic naming
$items = Order::find(1)->products;
// Domain-specific naming
$lineItems = Order::find(1)->products;

Common Pitfalls

Avoid Multiple Standards

Don't mix naming conventions for the same type of elements:

PHP
// Inconsistent
$user_id = 1;
$orderID = 100;
$productId = 25;
// Consistent (choose one style)
$userId = 1;
$orderId = 100;
$productId = 25;

Don't Reflect Type in Name

Modern IDEs provide type information, so don't include types in names:

PHP
// Unnecessary
$usersArray = User::all()->toArray();
$nameString = $user->name;
// Better
$users = User::all()->toArray();
$name = $user->name;

Avoid Unnecessary Context

Don't repeat the context that's already clear:

PHP
// Redundant context
class User {
public function getUserName() {...}
public function getUserEmail() {...}
}
// Better
class User {
public function name() {...}
public function email() {...}
}

Troubleshooting

Resolving Naming Conflicts

When you encounter naming conflicts:

  1. Consider adding more specific context
  2. Use namespaces to separate identical names in different contexts
  3. Refactor to better represent the domain concepts

Managing Legacy Code

When working with legacy code that doesn't follow these conventions:

  1. Follow existing patterns for modifications to maintain consistency
  2. Create style guides for new code
  3. Refactor incrementally when possible
Previous
Controller Best Practices