我试图实现编码密码的服务,但它似乎不工作,因为我得到"你已经请求了一个不存在的服务user_service "错误。
下面是我的代码: <标题>供应商/BundleNameBundle/资源/config/services.yml h1> app/config/config.yml h1> 的服务代码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);
编辑:我手动删除缓存文件夹,我的服务开始工作。
标题>尝试查看您的src/{VendorName}/{BundleName}Bundle/DependencyInjection/{VendorName}{BundleName}Extension.php
这个文件应该像这样加载你的服务定义:
<?php
namespace Vendor{BundleName}BundleDependencyInjection;
use SymfonyComponentDependencyInjectionContainerBuilder;
use SymfonyComponentConfigFileLocator;
use SymfonyComponentHttpKernelDependencyInjectionExtension;
use SymfonyComponentDependencyInjectionLoader;
/**
* 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 LoaderYamlFileLoader($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 {EnvName} DebugProjectContainer.php
- 应用。元
- 应用{EnvName} DebugProjectContainer.xml