← Tilbage til koncepter
Namespaces
Organisering af kode og undgåelse af navnekonflikter med namespaces
Kategori: Fundamentals
Foto: Martin Woortman / Unsplash
Key Points
- +Namespace declaration - Definer namespace i toppen af filen med namespace keyword
- +Use statements - Importer klasser fra andre namespaces for nem adgang
- +Aliasing - Giv importerede klasser et alternativt navn med as keyword
- +Global namespace - Root namespace uden præfiks, tilgås med backslash
- +Sub-namespaces - Hierarkisk organisering med backslash separator
- +Autoloading med PSR-4 - Automatisk mapping mellem namespaces og fil struktur
- +Namespace resolution - Fully qualified, qualified og unqualified navne
- +Multiple use declarations - Group use statements for samme namespace
- +Function og constant imports - Import ikke kun klasser men også funktioner og konstanter
- +Namespace conflicts - Håndter samme klassenavn fra forskellige namespaces med aliasing
Kode Eksempel
<?php
// File: src/Services/Email/EmailService.php
namespace App\Services\Email;
use App\Models\User;
use App\Contracts\MailerInterface;
use App\Exceptions\EmailException;
use DateTime;
use function sprintf;
use const PHP_EOL;
class EmailService implements MailerInterface {
private array $sent = [];
public function send(User $user, string $subject, string $body): bool {
try {
$message = sprintf(
"To: %s%sSubject: %s%s%s%s",
$user->email,
PHP_EOL,
$subject,
PHP_EOL,
PHP_EOL,
$body
);
$this->sent[] = [
'user' => $user->name,
'subject' => $subject,
'sent_at' => new DateTime()
];
echo "Email sent: {$subject}" . PHP_EOL;
return true;
} catch (\Exception $e) {
throw new EmailException("Failed to send email: " . $e->getMessage());
}
}
public function getSentCount(): int {
return count($this->sent);
}
}
// File: src/Models/User.php
namespace App\Models;
class User {
public function __construct(
public string $name,
public string $email
) {}
}
// Usage with group use statements
use App\Services\Email\{EmailService, EmailQueue};
use App\Models\{User, Order, Product};
$emailService = new EmailService();
$user = new User('John Doe', 'john@example.com');
$emailService->send($user, 'Welcome!', 'Thanks for signing up.');Hvornår bruges det?
- •Framework organisering - Laravel, Symfony og andre frameworks bruger namespaces til at strukturere deres komponenter
- •Package development - Composer packages bruger vendor\package namespace struktur
- •Large-scale applications - Opdel applikationen i moduler med hver sit namespace (Admin, API, Frontend)
- •Third-party integration - Undgå konflikter når multiple libraries har klasser med samme navn
- •Domain-driven design - Organiser kode efter business domæner (Billing, Shipping, Inventory)
- •Testing - Separate test namespaces (Tests\Unit, Tests\Feature) fra application kode
Best Practices
- +Følg PSR-4 standard for namespace til directory mapping - ét namespace per directory
- +Brug vendor navn som root namespace for packages (YourCompany\PackageName)
- +Hold namespace hierarkiet fladt - undgå for mange niveauer af sub-namespaces
- +Group related use statements sammen for bedre læsbarhed
- +Brug aliasing til at håndtere lange klassenavne eller navnekonflikter
- +Placer namespace declaration som første statement i filen (efter <?php)
- +Én klasse per fil med matching namespace og fil sti struktur
- +Brug leading backslash når du refererer til global namespace klasser (\DateTime, \Exception)
Quick Info
Kategori
Fundamentals
Sværhedsgrad
Begynder