laravel-interfaces-and-di

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Interfaces and Dependency Injection

接口与依赖注入

Define narrow interfaces and inject them where needed. Bind concrete implementations in a service provider.
php
interface Slugger { public function slug(string $s): string; }

final class AsciiSlugger implements Slugger {
  public function slug(string $s): string { /* ... */ }
}

$this->app->bind(Slugger::class, AsciiSlugger::class);
Benefits: easier testing (mock interfaces), clearer contracts, swap implementations without touching consumers.
定义职责单一的接口,并在需要的地方注入它们。在服务提供者中绑定具体的实现类。
php
interface Slugger { public function slug(string $s): string; }

final class AsciiSlugger implements Slugger {
  public function slug(string $s): string { /* ... */ }
}

$this->app->bind(Slugger::class, AsciiSlugger::class);
优势:更易于测试(可Mock接口)、契约更清晰、无需修改消费端即可替换实现类。