Попытка загрузить класс «BaseFixture» из пространства имен «App \ DataFixtures». Вы забыли оператор use для другого пространства имен? - PullRequest
0 голосов
/ 08 февраля 2020

Я пытаюсь использовать команду:

php bin/console do:fixtures:load

, чтобы добавить некоторые фиктивные данные в мой проект.

Однако, когда я вызываю команду, я получаю следующую ошибку.

Неустранимая ошибка: Uncaught Symfony \ Component \ Debug \ Exception \ ClassNotFoundException: Попытка загрузить класс "BaseFixture" из пространства имен "App \ DataFixtures". Вы забыли оператор use для другого пространства имен? в K: \рограммирование \ разработка \ testProject \ app \ src \ DataFixtures \ UserFixtures. php в строке 9

Symfony \ Component \ Debug \ Exception \ ClassNotFoundException: Попытка загрузить класс "BaseFixture" из пространства имен " App \ DataFixtures». Вы забыли оператор use для другого пространства имен? в K: \ программирование \ разработка \ testProject \ app \ src \ DataFixtures \ UserFixtures. php в строке 9

Стек вызовов: 0.1044 2464280 1. Symfony \ Component \ Debug \ ErrorHandler-> handleException () K : \ Программирование \ разработка \ testProject \ app \ vendor \ symfony \ debug \ ErrorHandler. php: 0

И я не могу понять проблему.

Вот мой BaseFixtures класс

  <?php

namespace App\DataFixtures;

use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Migrations\Version\Factory;
use Symfony\Bundle\MakerBundle\Generator;

abstract class BaseFixture extends Fixture
{
    /** @var ObjectManager */
    private $manager;

    /** @var Generator */
    protected $faker;

    private $referencesIndex = [];

    abstract protected function loadData(ObjectManager $manager);

    public function load(ObjectManager $manager)
    {
        $this->manager = $manager;
        $this->faker = Factory::create();

        $this->loadData($manager);
    }

    /**
     * Create many objects at once:
     *
     *      $this->createMany(10, function(int $i) {
     *          $user = new User();
     *          $user->setFirstName('Ryan');
     *
     *           return $user;
     *      });
     *
     * @param int      $count
     * @param string   $groupName Tag these created objects with this group name,
     *                            and use this later with getRandomReference(s)
     *                            to fetch only from this specific group.
     * @param callable $factory
     */
    protected function createMany(int $count, string $groupName, callable $factory)
    {
        for ($i = 0; $i < $count; $i++) {
            $entity = $factory($i);

            if (null === $entity) {
                throw new \LogicException('Did you forget to return the entity object from your callback to BaseFixture::createMany()?');
            }

            $this->manager->persist($entity);

            // store for usage later as groupName_#COUNT#
            $this->addReference(sprintf('%s_%d', $groupName, $i), $entity);
        }
    }

    protected function getRandomReference(string $groupName) {
        if (!isset($this->referencesIndex[$groupName])) {
            $this->referencesIndex[$groupName] = [];

            foreach ($this->referenceRepository->getReferences() as $key => $ref) {
                if (strpos($key, $groupName.'_') === 0) {
                    $this->referencesIndex[$groupName][] = $key;
                }
            }
        }

        if (empty($this->referencesIndex[$groupName])) {
            throw new \InvalidArgumentException(sprintf('Did not find any references saved with the group name "%s"', $groupName));
        }

        $randomReferenceKey = $this->faker->randomElement($this->referencesIndex[$groupName]);

        return $this->getReference($randomReferenceKey);
    }

    protected function getRandomReferences(string $className, int $count)
    {
        $references = [];
        while (count($references) < $count) {
            $references[] = $this->getRandomReference($className);
        }

        return $references;
    }

} ​​

А вот мой класс пользователя, который расширяет базовый класс.

    <?php

namespace App\DataFixtures;

use App\Entity\User;
use App\DataFixtures\BaseFixture;
use Doctrine\Common\Persistence\ObjectManager;

class UserFixtures extends BaseFixture
{
    protected function loadData(ObjectManager $manager)
    {
        $this->createMany(10, 'main_users', function ($i){
           $user = new User();
           $user->setEmail(sprintf('email%d@example.com', $i));
           $user->setFirstName($this->faker->firstName);

           return $user;
        });

        // $product = new Product();
        // $manager->persist($product);

        $manager->flush();
    }

}

Я, пожалуй, смотрю на это в течение долгого времени, и я не могу понять, в чем проблема.

...