【问题标题】:Service in Symfony2Symfony2 中的服务
【发布时间】:2012-10-04 12:00:28
【问题描述】:

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

服务.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);

类 locationManager :

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". 

【问题讨论】:

    标签: symfony symfony-2.1


    【解决方案1】:

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

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

    【讨论】:

    • 不,这只是我写消息时的错误,我知道但问题不在这里,请问还有其他解决方案吗?
    【解决方案2】:

    你真的加载了 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');
    }
    

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

    更多信息请见herehere

    【讨论】:

    • 如果你在控制台中使用php app/console container:debug调试容器会发生什么?
    • 您可以编辑您的问题并发布整个MyAppMyBundleExtension 课程吗?我认为问题就在那里......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2014-10-29
    相关资源
    最近更新 更多