1

我想创建一个容器服务,所以我使用带有构造函数的类:

服务.xml:

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
    <parameter key="myapp_mybundle.locationmanager.class">My_app\MyBundle\Manager\LocationManager</parameter>
    <parameter key="myapp_mybundle.rootLocation">rootLocation</parameter>
</parameters>

<services>
    <service id="myapp_mybundle.locationmanager" class="%myapp_mybundle.locationmanager.class%">
    <argument>%myapp_mybundle.rootLocation%</argument>

    </service>
</services>

MyappMyBundleExtension.php

$container->set('myapp_mybundle.locationmanager', $manager);

类位置管理器:

class LocationManager
{
     /**
     * @var Location
     */
protected $rootLocation;

public function __construct(Location $rootLocation)
{
    $this->rootLocation = $rootLocation;
}
   .....

以及控制器中的一些操作:

   $locationManager =  $this->container->get("myapp_mybundle.locationmanager");

我收到此错误:

  You have requested a non-existent service "myapp_mybundle.locationmanager". 
4

2 回答 2

0

你真的加载了 services.xml 文件吗?

像这样:

use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;

public function load(array $configs, ContainerBuilder $container)
{
    $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
    $loader->load('services.xml');
}

如果你不这样做,你的服务就不会注入到容器中,你将无法加载它们。

可以在此处此处找到有关此的更多信息。

于 2012-10-04T13:39:20.487 回答
0

您的服务没有大写的“b”...应该是

$locationManager = $this->container->get("myapp_mybundle.locationmanager");

于 2012-10-04T12:41:42.787 回答