【发布时间】:2017-04-19 15:57:52
【问题描述】:
我对 Symfony DependencyInjection 组件有疑问。我想将接口注入控制器,所以我只能使用接口方法。但是,我注意到我可以使用实现接口的类中的任何公共方法,这是错误的。我关注了伟大的文章:http://php-and-symfony.matthiasnoback.nl/2014/05/inject-a-repository-instead-of-an-entity-manager/
编写测试服务类和接口
interface ITestService
{
public function interfaceFunction();
}
class TestService implements ITestService
{
public function interfaceFunction() {/* do somenthing */}
public function classFunction() {/*do somenthing*/}
}
将我的应用程序服务类配置为服务 (test_service)
# file: app/config/services.yml
test_service:
class: MyApp\Application\Services\TestService
将我的控制器配置为服务:
# file: app/config/services.yml
test_controller:
class: MyApp\AppBundle\Controller\TestController
arguments:
- '@test_service'
在控制器中使用服务
class TestController extends Controller
{
private testService;
function _construct(ITestService $testService)
{
$this->testService = $testService;
}
public function indexAction()
{
// This should be inaccesible but it works :(
$this->testService->classFunction();
// This is the only function I should use.
$this->testService->interfaceFunction();
}
【问题讨论】:
-
我认为
OOP中不存在这样的概念。您可以尝试使用traits 但 afaik 那些不是类型提示... -
为什么不能访问?
$testService仍然是TestService类的对象,无论该类是否实现了某些接口。 -
谢谢,@JovanPerovic 和 yoshi。好吧,在我的构造函数中,我正在等待一个带有 ITestService 合同的对象。我应该放弃本合同中不存在的任何方法。我使用 c# 和城堡 Windsor IoC 框架,我只能使用接口中定义的方法。这对我来说很有意义,但是 symfony 组件让我感到困惑。
-
这是一个 PHP 问题。就像实现接口和对象的方式一样。您的 IDE 至少应该阻止您使用非接口方法。
-
PHP 解析方法以在运行时调用。您不需要明确的downcasting 对象类,例如Java 或C++。事实上,您根本不需要指定类型提示:方法会很好地工作。类型提示是运行时检查、方法签名的契约。
标签: dependency-injection interface symfony