在配置文件services.yaml中,我创建了几个具有名称的服务
cart.storage.session:
class: App\Cart\Storage\SessionStorage
arguments:
- '%cart.storage.session_key%'
cart.calculator:
class: App\Cart\Cost\SimpleCost
cart:
class: App\Cart\Cart
arguments:
- '@cart.storage.session'
- '@cart.calculator'
我在我的控制器中使用这些服务
$cart = $this->container->get('cart');
但是由于某种原因,通过这样的服务调用,我得到了一个例外。
服务“cart”未找到:即使它存在于应用程序的容器中,“App\Controller\CartController”中的容器是一个较小的服务定位器,只知道“doctrine”、“http_kernel”、“parameter_bag”、“request_stack” ”、“路由器”、“security.authorization_checker”、“security.csrf.token_manager”、“security.token_storage”和“session”服务。尝试改用依赖注入。
bin/console debug:container命令显示容器包含我的服务,但由于某种原因它们没有命名
-------------------------------------------------------------
Service ID Class name
--------------------------------------------------------------
App\Cart\Cart App\Cart\Cart
App\Cart\CartItem App\Cart\CartItem
App\Cart\Cost\BigCost App\Cart\Cost\BigCost
App\Cart\Cost\BirthdayCost App\Cart\Cost\BirthdayCost
App\Cart\Cost\DummyCost App\Cart\Cost\DummyCost
App\Cart\Cost\FourCost App\Cart\Cost\FourCost
App\Cart\Cost\FridayCost App\Cart\Cost\FridayCost
App\Cart\Cost\MinCost App\Cart\Cost\MinCost
App\Cart\Cost\NewYearCost App\Cart\Cost\NewYearCost
App\Cart\Cost\SimpleCost App\Cart\Cost\SimpleCost
App\Cart\Storage\DBStorage App\Cart\Storage\DBStorage
App\Cart\Storage\HybridStorage App\Cart\Storage\HybridStorage
App\Cart\Storage\MemoryStorage App\Cart\Storage\MemoryStorage
App\Cart\Storage\SessionStorage App\Cart\Storage\SessionStorage
App\Controller\CartController App\Controller\CartController
然后我改变了我的services.yaml如下
cart.storage.session:
class: App\Cart\Storage\SessionStorage
arguments:
- '%cart.storage.session_key%'
App\Cart\Storage\SessionStorage: '@cart.storage.session'
cart.calculator:
class: App\Cart\Cost\SimpleCost
App\Cart\Cost\SimpleCost: '@cart.calculator'
cart:
class: App\Cart\Cart
arguments:
- '@cart.storage.session'
- '@cart.calculator'
App\Cart\Cart: '@cart'
之后,我的服务获得了名称,并且bin/console debug:container命令开始显示以下内容
-------------------------------------------------------------
Service ID Class name
--------------------------------------------------------------
App\Cart\Cart alias for "cart"
App\Cart\CartItem App\Cart\CartItem
App\Cart\Cost\BigCost App\Cart\Cost\BigCost
App\Cart\Cost\BirthdayCost App\Cart\Cost\BirthdayCost
App\Cart\Cost\DummyCost App\Cart\Cost\DummyCost
App\Cart\Cost\FourCost App\Cart\Cost\FourCost
App\Cart\Cost\FridayCost App\Cart\Cost\FridayCost
App\Cart\Cost\MinCost App\Cart\Cost\MinCost
App\Cart\Cost\NewYearCost App\Cart\Cost\NewYearCost
App\Cart\Cost\SimpleCost alias for "cart.calculator"
App\Cart\Storage\DBStorage App\Cart\Storage\DBStorage
App\Cart\Storage\HybridStorage App\Cart\Storage\HybridStorage
App\Cart\Storage\MemoryStorage App\Cart\Storage\MemoryStorage
App\Cart\Storage\SessionStorage alias for "cart.storage.session"
App\Controller\CartController App\Controller\CartController
但它仍然没有解决这种情况,因为我仍然得到与以前相同的异常。
找不到服务“购物车”:即使它存在于应用程序的容器中,里面的容器