首页 > 解决方案 > 在服务类中使用 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. 

标签: phpsymfonysymfony5

解决方案


根据最新的编辑,错误很明显:如果你想使用依赖注入,你必须使用它。没有任何构造函数参数的调用$rotate = new Rotate();将失败,因为 Symfony 无法为您注入它们。

相反,通过操作注入它:

public function profile(UserInterface $user, Rotate $rotate)

ParameterBagInterface...如果您启用了自动装配,这将使用 Symfony 的容器并注入. 如果没有,您必须编写正确的服务定义来完成这项工作


推荐阅读