2012-10-04 46 views
1

我想創建一個集裝箱業務,所以我就用CLASSE一個構造器:服務中的Symfony2

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

回答

0

你的服務沒有大寫的 「B」 ......應該是

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

+0

不,這只是一個錯誤,當我寫我的消息,我知道,但它不是這裏的問題,所以任何其他的解決方案,請嗎? – Nll

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'); 
} 

如果你不這樣做,你的服務不注入容器,你將無法加載它們。

有關這方面的更多信息可以發現herehere

+0

是sis已經存在! – Nll

+2

如果使用'php app/console container:debug'調試控制檯中的容器會發生什麼? –

+0

我做了,但沒有列出我的服務名稱...... – Nll