PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label symfony-dependency-injection. Show all posts
Showing posts with label symfony-dependency-injection. Show all posts

Wednesday, May 11, 2022

[FIXED] How can I use a class constant as the tag for bound parameter service?

 May 11, 2022     php, symfony, symfony-dependency-injection, symfony4     No comments   

Issue

I have tagged a group of services that implement the same interface like this in my configuration:

// services.yml
services:
  _instanceof:
     App\SomeInterface:
       tags: [ !php/const App\SomeInterface::TAG ]

(Where the value for App\SomeInterface::TAG is very_unique_identifier)

I would like to reuse this value to bind this parameter like this:

// services.yaml
 services:
  _defaults:
    autowire: true      
    autoconfigure: true 
    public: false
    bind:
      $fooStrategies: !tagged !php/const App\SomeInterface::TAG 

But when I do it like this, I get an empty RewindableGenerator.

Instead I can do it like this, using the literal value for the constant:

bind:
      $fooStrategies: !tagged 'very_unique_identifier'

... and it works as expected, and the RewindableGenerator has all the necessary services inside.

How can I use the PHP constant in both places, so I do not have to repeat the value in different places? Obviously, not a huge deal, but I'd like to avoid it if possible.


Solution

You should be able to configure a parameter with the value !php/const App\SomeInterface::TAG and then use the parameter name in service.yml.

parameters.yml

parameters:
    interfaceTag: !php/const App\SomeInterface::TAG

and then

services.yml

services:
  _defaults:
     autowire: true      
     autoconfigure: true 
     public: false
     bind:
       $fooStrategies: !tagged '%interfaceTag%'


Answered By - NorthernDev
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to represent argument that uses factory with YAML configuration, equivalent to this XML configuration?

 May 11, 2022     dependency-injection, php, symfony, symfony-dependency-injection     No comments   

Issue

I am trying to figure out if I can use a similar construct in the YAML syntax for a service definition as in the XML syntax. Specifically the "construct" where, in XML, an argument can be resolved by factory "in-line".

I have the following XML definition:

<service id="my_service_id" class="App\Some\Service">
    <argument type="service">
        <service class="Gaufrette\Filesystem">
            <argument>%some_container_parameter%</argument>
            <factory service="knp_gaufrette.filesystem_map" method="get" />
        </service>
    </argument>
    <argument type="service" id="request_stack"/>
    <argument>%some_other_container_parameter%</argument>
</service>

I can't figure out how to represent this (or if it's even possible) in yaml.

I have tried the following:

my_service_id:
    class: App\Some\Service
    arguments:
        - { class: Gaufrette\Filesystem, factory: ['@knp_gaufrette.filesystem_map','get'], arguments: ['%some_container_parameter%'] }
        - '@request_stack'
        - '%some_other_container_parameter%'

but that gives me the following error message:

Argument 1 passed to App\Some\Service::__construct() must implement interface Gaufrette\FilesystemInterface, array given


Solution

You are defining two services within the same definition in the XML version.

While that is possible in XML, I don't really think it's a great idea. You can easily do the same by defining each service on its own:

gaufrette.filesystem:
    factory: ['@knp_gaufrette.filesystem_map','get']
    arguments: ['%some_container_parameter%']

my_service_id:
    class: App\Some\Service
    arguments:
        - '@gaufrette.filesystem'
        - '@request_stack'
        - '%some_other_container_parameter%'


Answered By - yivi
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 12, 2022

[FIXED] The > "Symfony\Component\DependencyInjection\ContainerInterface" autowiring > alias is deprecated. How eliminate it on symfony 5.1?

 March 12, 2022     php, symfony, symfony-dependency-injection     No comments   

Issue

I am migrating an application from Symfony 4.4 to Symfony 5.4. In the case of forms, I have a form that I pass in the constructor a variable ContainerInterface $container to use a parameter in the configuration of a widget. In version 5.4 this gives me a deprecation warning:

Since symfony/dependency-injection 5.1: The "Symfony\Component\DependencyInjection\ContainerInterface" autowiring alias is deprecated. Define it explicitly in your app if you want to keep using it. It is being referenced by the "App\Form\BuscarAvanzadaNinhoType" service.

How do I solve it?

class BuscarAvanzadaNinhoType extends AbstractType {

    private $em;
    private $security;
    private $uuidEncoder;
    private $container;

    public function __construct(ManagerRegistry $em, Security $security, UuidEncoder $uuidEncoder, ContainerInterface $container) {
        $this->em = $em;
        $this->security = $security;
        $this->uuidEncoder = $uuidEncoder;
        $this->container = $container;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
               
                ->add('otrosAspectos', Select2EntityType::class, array(
                    'class' => EtiquetaAspectoNinho::class,
                    'remote_route' => 'ninhos_encontrarEtiquetaAspectos',
                    'primary_key' => 'id',
                    'text_property' => 'text',
                    'multiple' => true,
                    'allow_clear' => false,
                    'delay' => 250,
                    'cache' => false,
                    'minimum_input_length' => 3,
                    'scroll' => true,
                    'page_limit' => $this->container->getParameter('limite_resultados_etiquetas'),
                    'language' => 'es',
                    'width' => '100%',
                    'placeholder' => '',
                        )
        );

        
    }

    

}

Solution

You can pass parameters directly without the container.

public function __construct(ManagerRegistry $em, Security $security, UuidEncoder $uuidEncoder, array $formParams) {
    $this->em = $em;
    $this->security = $security;
    $this->uuidEncoder = $uuidEncoder;
    $this->formParams = $formParams;
}

services.yml

services:
    _defaults:
        autowire: true
        autoconfigure: true
        bind:
            $formParams:
                limite_resultados_etiquetas: '%limite_resultados_etiquetas%'

In the form:

'page_limit' => $this->formParams['limite_resultados_etiquetas'],


Answered By - Artem
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 10, 2022

[FIXED] Circular reference problem with decorated service

 January 10, 2022     api-platform.com, php, symfony, symfony-dependency-injection     No comments   

Issue

As the documentation suggests I wrote this service to add the uuid to the normalized object:

<?php
namespace App\Serializer;

use InvalidArgumentException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;

final class ApiNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface
{
    private DenormalizerInterface|NormalizerInterface $decorated;

    public function __construct(NormalizerInterface $decorated)
    {
        if (!$decorated instanceof DenormalizerInterface) {
            throw new InvalidArgumentException(sprintf('The decorated normalizer must implement the %s.', DenormalizerInterface::class));
        }

        $this->decorated = $decorated;
    }

    public function supportsNormalization($data, $format = null)
    {
        return $this->decorated->supportsNormalization($data, $format);
    }

    public function normalize($object, $format = null, array $context = [])
    {
        $data = $this->decorated->normalize($object, $format, $context);
        if(method_exists($object, 'getUuid') && is_array($data)){
            $data['uuid'] = $object->getUuid();
        }
        return $data;
    }

    /**
     * @param mixed $data
     * @param string $type
     * @param null $format
     *
     * @return bool
     */
    public function supportsDenormalization($data, $type, $format = null)
    {
        return $this->decorated->supportsDenormalization($data, $type, $format);
    }

    public function denormalize($data, $type, $format = null, array $context = [])
    {
        return $this->decorated->denormalize($data, $type, $format, $context);
    }

    public function setSerializer(SerializerInterface $serializer)
    {
        if($this->decorated instanceof SerializerAwareInterface) {
            $this->decorated->setSerializer($serializer);
        }
    }
}

And services.yaml

App\Serializer\ApiNormalizer:
    # By default .inner is passed as argument
    decorates: 'api_platform.jsonld.normalizer.item'

But suddenly (until yesterday everything was fine) it starts to give me this error when I run composer or cache clear

In CheckCircularReferencesPass.php line 67: Circular reference detected for service "App\Serializer\ApiNormalizer", path: "App\Serializer\ApiNormalizer -> serializer -> App\Serializer\ApiNormalizer".


Solution

This is an issue with Symfony Dependency Injection component on version 5.3.7.

https://github.com/symfony/symfony/issues/42792

This is likely going to be resolved tomorrow or the day after.

On the meantime, just add this to your composer.json:

"conflict": {
    "symfony/dependency-injection": "5.3.7"
},

This way you can keep the rest of the dependencies updated, and it will just exclude DI 5.3.7 in favour of 5.3.6.

When 5.3.8 is released, you'll be able to update directly.



Answered By - yivi
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Symfony: Use a value within a parameter array as a service parameter

 January 10, 2022     symfony, symfony-3.4, symfony-dependency-injection     No comments   

Issue

Symfony 3.4

I have a parameter that looks like this:

parameters.yml:

paramters:
    some_configuration:
        param1: value1
        param2: value2

I want to pass a value within my some_configuration parameter directly to a service, rather that some_configuration itself. Something like this:

services.yml:

services:
    AppBundle\Service\MyService:
        arguments:
            $serviceparam: '%some_configuration.param2%'

Is this possible somehow?


Solution

Above Symfony 2.7.3

In all the Symfony config files I've seen, the entries under 'parameters:' have always been fully qualified.
I don't fully understand why this is but it may help you to write the entries in your parameters.yml like this:

parameters.yml:

parameters:
    some_configuration.param1: value1
    some_configuration.param2: value2

To use parameter array values in service.yaml you can use it as a normal parameter (like what you've written!):

service.yaml

services:
    AppBundle\Service\MyService:
        arguments:
            $serviceparam: '%some_configuration.param2%'

In symfony 2.7.3:

It can be accomplished the following way:

services:
    AppBundle\Service\MyService:
        arguments:
            $serviceparam: ["@=container.getParameter('some_configuration')['param1']"]

It works for symfony 2.7.3
More info about the expression language can be found in the symfony doc



Answered By - Amir Shamsi
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing