我需要创建一个服务,它使用另一个工厂服务,并返回不同类型的对象。
这是我的服务的定义:
services:
games.search_factory:
class: %games.search_factory.class%
calls:
- [ setContainer, ["@service_container"] ]
games.search:
class: %games.search.base.class%
factory_service: games.search_factory
factory_method: get
我的
%games.search_factory.class%
get 方法根据请求参数返回不同的对象。我的
%games.search.base.class%
是抽象的。我的目标是 - 当我打电话时
$this->get("games.search");
我想得到工厂方法的结果。但是当我运行代码时,我得到一个错误: FatalErrorException:错误:无法实例化抽象类 .
所以我有两个问题:
更新:我在代码部分有一个错误,这里没有显示。除了这两个用于搜索的服务之外,我还为每种搜索类型提供了一个服务,并从工厂返回了这些服务。但是在这些服务的定义中,我使用了我的基类(它是抽象的)作为一个类。
很好的结论是可以从工厂返回不同类型的对象。
最佳答案
从这里:http://symfony.com/doc/current/components/dependency_injection/factories.html
When you specify the class to use for the factory (via factory_class) the method will be called statically. If the factory itself should be instantiated and the resulting object's method called (as in this example), configure the factory itself as a service
为了将容器注入(inject)您的工厂,您需要使工厂可实例化(非抽象)或将容器作为参数传递给静态 get 方法。我不知道有什么方法可以将服务声明为静态的。
关于symfony - Service(使用服务工厂)返回不同类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15642572/