Getting started with PHP-DI
(开始使用PHP-DI)
Welcome! This guide will help you get started with using PHP-DI in your project.
Before beginning, you need to know what dependency injection is. If you don't, there's a whole article dedicated to it: Understanding dependency injection.
(欢迎光临!本指南将帮助您在项目中开始使用PHP-DI。
在开始之前,您需要知道依赖注入是什么。如果你还不了解它的含义,这里有一整篇文章专门介绍它:理解依赖注入)
Installation
(安装)
Install PHP-DI with Composer:
(使用composer安装PHP-DI)
composer require php-di/php-di
PHP-DI requires PHP 7.0 or above.
(PHP-DI需要PHP 7.0或者更高)
Basic usage
(基本用法)
1. Use dependency injection
(使用依赖注入)
First, let's write code using dependency injection without thinking about PHP-DI:
(首先,让我们在不考虑PHP-DI的情况下使用依赖注入编写代码:)
class Mailer
{
public function mail($recipient, $content)
{
// send an email to the recipient
}
}
class UserManager
{
private $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
public function register($email, $password)
{
// The user jus