php - 在服务类中使用 Symfonybundle 中的参数
问题描述
我有名为上传图片的 Symfony 包:
我想在我的班级中使用我的包中的参数。
这是我的参数文件:
upload-images:
image:
crop_size: 300
我的文件:
配置.php
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('upload-images');
$treeBuilder->getRootNode()
->children()
->arrayNode('image')
->children()
->integerNode('save_original')->end()
->scalarNode('crop_size')->end()
->end()
->end() // twitter
->end();
return $treeBuilder;
}
}
UploadImagesExtension.php
class UploadImagesExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources'));
$loader->load('services.yaml');
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
}
}
最后我的服务类:
旋转.php
在这个类中,我想要参数:crop_size
我尝试了 ParameterBagInterface:
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class Rotate
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function Rotate()
{
$cropSize = $params->get('crop_size');
}
}
用户控制器.php
use verzeilberg\UploadImagesBundle\Service\Rotate;
class UserController extends AbstractController
{
/** @var UserProfileService */
private $service;
private $userService;
public function __construct(
UserProfileService $service,
UserService $userService
) {
$this->service = $service;
$this->userService = $userService;
}
/**
* @param UserInterface $user
* @return Response
*/
public function profile(UserInterface $user)
{
$rotate = new Rotate();
$rotate->Rotate();
.....
...
}
Getting this error:
函数 verzeilberg\UploadImagesBundle\Service\Rotate::__construct() 的参数太少,在第 62 行的 /home/vagrant/projects/diabetigraph-dev/src/Controller/User/UserController.php 中传递了 0,而预期的正好是 1
I have search for a solution. But did not came accross the right one.
解决方案
根据最新的编辑,错误很明显:如果你想使用依赖注入,你必须使用它。没有任何构造函数参数的调用$rotate = new Rotate();
将失败,因为 Symfony 无法为您注入它们。
相反,通过操作注入它:
public function profile(UserInterface $user, Rotate $rotate)
ParameterBagInterface
...如果您启用了自动装配,这将使用 Symfony 的容器并注入. 如果没有,您必须编写正确的服务定义来完成这项工作
推荐阅读
- asp.net - 是否可以使用 dotNet 使用 Hangfire 每 20 秒运行一次作业?
- javascript - 如何在 FullCalendar 的每一行之前添加自定义 HTML?
- php - PhpUnit 无权访问公共目录
- html - 隐藏网格列,其余列重新分配
- angular - 是否可以根据条件从抽象模型中忽略/替换验证器?
- c++ - 通过基类指针进行奇怪的模板类转换
- javascript - 更改悬停点上标记的颜色 - Highcharts
- html - 我们与 AdSense html 代码有什么关系
- java - 如何在 JPA 中编写动态 sql 查询以从 jsonb 列中查询数据?
- java - Codemagic 错误 无效的加密密钥 - 加密的变量仅适用于创建它们的同一团队中的构建