在PHP中,依赖注入(Dependency Injection,简称DI)是一种设计模式,用于降低代码之间的耦合度。在Spring框架中,依赖注入通常通过构造函数注入、属性注入和方法注入来实现。以下是如何在PHP中使用Spring框架实现依赖注入的示例:
composer require spring-framework/di
MessageService
接口和一个EmailService
实现类:namespace App\Services;
interface MessageService
{
public function sendMessage(string $message);
}
class EmailService implements MessageService
{
public function sendMessage(string $message)
{
echo "Sending email: {$message}\n";
}
}
Bean
定义来配置依赖关系。创建一个App\Services\MessageServiceProvider
类,用于定义MessageService
的Bean:namespace App\Services;
use Spring\Di\Annotation\Bean;
use Spring\Di\Annotation\Autowired;
use Spring\Di\Container\AnnotationContainer;
class MessageServiceProvider
{
/**
* @Autowired
* @var Container
*/
private $container;
public function __construct(AnnotationContainer $container)
{
$this->container = $container;
}
/**
* @Bean
* @param EmailService $emailService
* @return MessageService
*/
public function messageService(EmailService $emailService)
{
return $emailService;
}
}
MessageServiceProvider
。创建一个名为app.yml
的配置文件,并添加以下内容:services:
App\Services\MessageServiceProvider:
arguments:
- App\Services\EmailService
MessageService
,Spring会自动注入EmailService
实现类:namespace App\Controllers;
use App\Services\MessageService;
class HomeController
{
private $messageService;
public function __construct(MessageService $messageService)
{
$this->messageService = $messageService;
}
public function index()
{
$this->messageService->sendMessage("Hello, dependency injection!");
}
}
index.php
的文件,并添加以下内容:<?php
require_once 'vendor/autoload.php';
use Spring\Di\Container\AnnotationContainer;
use Spring\Di\Container\ContainerBuilder;
$containerBuilder = new ContainerBuilder();
$containerBuilder->addConfiguration(new \Spring\Di\Config\XmlConfiguration('app.yml'));
$container = $containerBuilder->build();
$container->get('App\Controllers\HomeController');
现在,当你访问index.php
时,Spring会自动处理依赖注入并调用HomeController
。