我想创建一个容器服务,所以我使用了带有构造函数的classe:
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);
class 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 :(得分:0)
您的服务没有大写“b”......应该是
$locationManager = $this->container->get("myapp_mybundle.locationmanager");
答案 1 :(得分: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');
}
如果您不这样做,您的服务不会注入容器,您将无法加载它们。