laravel-interfaces-and-di
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseInterfaces 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);优势:更易测试(可模拟接口)、更清晰的契约、无需修改消费者即可替换实现。