简体   繁体   中英

Container is non-object error in Symfony data fixtures

I'm trying to access to the service api.service.feedback in fixture class below but for some reason container returns error below on if statement in load() method:

ERROR: PHP Fatal error: Call to a member function has() on a non-object

Note: If anyone wants to know, the service api.service.feedback itself is accessible in all the controllers and has no problem with it.

<?php

namespace .........;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadOrderFixtures extends AbstractFixture implements FixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        if ($this->container->has('api.service.feedback')) {
            exit('EXISTS');
        }
     }

     ......
}

You are just implementing the ContainerAwareInterface. If you want the container, you have to inject it:

services:
    bundle.service_name: 
        class: ...
        calls:
            - [ setContainer, [ @service_container ] ]

You can extend directly ContainerAware:

class LoadArticlesData extends ContainerAware implements FixtureInterface, OrderedFixtureInterface {

    public function load(ObjectManager $manager)
    {
        $dummy = $this->container->getParameter('dynamic.dummy');
        ...   
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM