Search code examples
symfonyshopwareshopware6shopware6-api

Too few arguments to function ReadingData::__construct(), 1 passed in ... KernelDevDebugContainer.php on and exactly 2 expected


I created a Service to read data from the database. In order to achieve that, I want to make a Controller and throw this controller I want to call first the ReadingDataService.

Error Message:

Too few arguments to function TryPlugin\Service\ReadingData::__construct(), 1 passed in /var/www/html/var/cache/dev_he0523cc28be2f689acaab5c325675d68/ContainerFt0wDoq/Shopware_Production_KernelDevDebugContainer.php on line 25455 and exactly 2 expected

Code:
ReadingData.php

class ReadingData
{
    private EntityRepositoryInterface $productRepository;
    private Context $con;

    public function __construct(EntityRepositoryInterface $productRepository, Context $con)
    {
        $this->productRepository = $productRepository;
        $this->con = $con;
    }

    public function readData(): void
    {
        $criteria1 = new Criteria();
        $products = $this->productRepository->search($criteria1, $this->con)->getEntities();

    }

}

PageController.php

/**
 * @RouteScope (scopes={"storefront"})
 */
class PageController extends StorefrontController
{
    
    /**
     * @Route("/examples", name="examples", methods={"GET"})
     */
    public function showExample(ReadingData $ReadingDatan): Response
    {
        $meinData = $ReadingDatan->readData();
        return $this->renderStorefront('@Storefront/storefront/page/content/index.html.twig', [
            'products' => $meinData,
        ]);
    }
}

Service.xml:

<service id="TryPlugin\Service\ReadingData">
    <argument type="service" id="product.repository"/>
</service>

<!--ReadingDate From Controller-->
<service id="TryPlugin\Storefront\Controller\PageController" public="true">
    <call method="setContainer">
        <argument type="service" id="service_container"/>
    </call>
    <tag name="controller.service_arguments"/>
</service> 

Solution

  • You need to pass the 2nd argument in service.xml

    Your class requires two arguments:

    public function __construct(EntityRepositoryInterface $productRepository, Context $con) { //...
    

    but only provides one in service.xml:

    <service id="TryPlugin\Service\ReadingData">
        <argument type="service" id="product.repository"/>
        <!-- Need argument for `Context $con` -->
    </service>
    

    Looking at the documentation, Context does not appear to be autowired by default.

    Therefore, you must inject the service yourself in service.xml.

    If you grow tired of all ways specifying the arguments in service.xml, look into enabling and configuring autowire for ShopWare.