您已请求不存在的服务" user_service"

时间:2014-07-02 00:13:27

标签: php symfony symfony-2.5

Iam尝试实施密码编码服务,但似乎它没有工作因为我得到了#34;你已经请求了一个不存在的服务user_service"错误。

这是我的代码:

供应商/ BundleNameBundle /资源/配置/ services.yml

services:
    user_service:
         class:  Morescreens\VideomanagerBundle\Service\UserService
         arguments: ['@security.encoder_factory']

的应用程序/配置/ config.yml

imports:
    - { resource: "@morescreensVideomanagerBundle/Resources/config/services.yml" }

我服务的代码

class UserService {

    /**
     * @var EncoderFactoryInterface
     */
    private $encoderFactory;



    public function  __construct(EncoderFactoryInterface $encoderFactory)
    {
           $this->encoderFactory=$encoderFactory;
    }


    public  function  setEncodedPassword(User $user)
   {
         $encoder=$this->encoderFactory->getEncoder($user);
         $password=$encoder->encodePassword($user->getPassword(),$user->getSalt());
         $user->setPassword($password);
   }

}

我的控制器内部:

 $user=new User();
        $user->setPassword('password');

        $this->get('user_service')->setEncodedPassword($user);

编辑:

我手动删除了缓存文件夹,我的服务开始工作。

1 个答案:

答案 0 :(得分:5)

尝试查看你的src / {VendorName} / {BundleName} Bundle / DependencyInjection / {VendorName} {BundleName} Extension.php

此文件应加载您的服务定义,如下所示:

<?php

namespace Vendor\{BundleName}Bundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class Vendor{BundleName}Extension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        //Load our YAML resources
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}

这会将服务定义从src/{VendorName}/{BundleName}Bundle/Resources/config/services.yml加载到容器中。如果仍然无效,请尝试php app/console cache:clear。出于速度原因,symfony基本上会将您的所有服务(和其他配置文件)聚合到一个缓存文件中,因此它不必每次都读取这些文件。实际缓存服务定义的文件位于:

  • app / cache / {envName} /(可以将缓存目录配置为位于您想要的任何位置,这只是默认设置。)

具有容器服务定义的相关信息的文件是:

  • 应用{ENVNAME} DebugProjectContainer.php
  • app {EnvName} DebugProjectContainer.php.meta
  • 应用{ENVNAME} DebugProjectContainer.xml