Класс App \ Repository \ UsersRepository не найден в цепочке настроенных пространств имен App \ Document - PullRequest
0 голосов
/ 06 мая 2020

Я пытаюсь настроить подключение Symfony 5.0.8 с MongoDB для api. Если вызвать пользователя регистрации из браузера, я вернул эту ошибку.

Класс 'App \ Repository \ UsersRepository' не был найден в цепочке настроенных пространств имен App \ Document

Эта ошибка возникает, если написать следующий код:

            /* @var UsersRepository $Users */
            $Users = $documentManager->getRepository(Users::class);

Это мои настройки:

Document \ Users

<?php

namespace App\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as Mongodb;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @Mongodb\Document(collection="users", repositoryClass="App\Repository\UsersRepository")
 * */
class Users implements UserInterface
{
    /**
     * @Mongodb\Id
     * */
    protected $id;

    /**
     * @Mongodb\Field(type="string", nullable=false)
     * */
    protected $email;

    /**
     * @Mongodb\Field(type="string", nullable=false)
     * */
    protected $firstName;

    /**
     * @Mongodb\Field(type="string", nullable=false)
     * */
    protected $lastName;

    /**
     * @Mongodb\Field(type="string", nullable=false)
     * */
    protected $password;

    /**
     * @Mongodb\Field(type="string")
     * */
    protected $city;

    /**
     * @Mongodb\Field(type="string")
     * */
    protected $state;

    /**
     * @Mongodb\Field(type="array", nullable=false)
     * */
    private $roles = [];

    /**
     * @return string
     * */
    public function getId(): ?string
    {
        return (string) $this->id;
    }

    /**
     * @see UserInterface
     *
     * @return string
     * */
    public function getUsername()
    {
        return "{$this->email}";
    }

    /**
     * @param string $email
     *
     * @return self
     * */
    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * @see UserInterface

     * @return string
     * */
    public function getEmail(): ?string
    {
        return (string) $this->email;
    }

    /**
     * @param string $firstName
     *
     * @return self
     * */
    public function setFirstName(string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * @return string
     * */
    public function getFirstName(): ?string
    {
        return (string) $this->firstName;
    }

    /**
     * @param string $lastName
     *
     * @return self
     * */
    public function setLastName(string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * @return string
     * */
    public function getLastName(): ?string
    {
        return (string) $this->lastName;
    }

    /**
     * @param string $password
     *
     * @return self
     * */
    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     * */
    public function getPassword()
    {
        return (string) $this->password;
    }

    /**
     * @param string $city
     *
     * @return self
     * */
    public function setCity(string $city): self
    {
        $this->city = $city;

        return $this;
    }

    /**
     * @return string
     * */
    public function getCity(): ?string
    {
        return (string) $this->city;
    }

    /**
     * @param string $state
     *
     * @return self
     * */
    public function setState(string $state): self
    {
        $this->state = $state;

        return $this;
    }

    /**
     * @return string
     * */
    public function getState(): string
    {
        return (string) $this->state;
    }

    /**
     * @see UserInterface
     *
     * @return array
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    /**
     * @param array $roles
     * @return self
     * */
    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }
}

Репозиторий \ Пользователи

<?php


namespace App\Repository;


use App\Document\Users;
use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
use Doctrine\Bundle\MongoDBBundle\Repository\ServiceDocumentRepository;
use Doctrine\ODM\MongoDB\LockMode;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @method Users|null find($id, int $lockMode = LockMode::NONE, ?int $lockVersion = null) : ?object
 * @method Users|null findOneBy(array $criteria) : ?object
 * @method Users[] findAll() : array
 * @method Users[] findBy(array $criteria, ?array $sort = null, $limit = null, $skip = null) : array
 */
class UsersRepository extends ServiceDocumentRepository implements PasswordUpgraderInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Users::class);
    }

    public function upgradePassword(UserInterface $user, string $newEncodedPassword): void
    {
        if (!$user instanceof Users) {
            throw new UnsupportedUserException(sprintf("Instances of \"%s\" are not supported.", \get_class($user)));
        }

        $user->setPassword($newEncodedPassword);
        $this->getDocumentManager()->persist($user);
        $this->getDocumentManager()->flush();
    }

    /**
     * @param string $email
     * @param string $password
     * @param string $firstName
     * @param string $lastName
     * @param string $city
     * @param string $state
     *
     * @return void
     * */
    public function createUser(string $email, string $password, string $firstName, string $lastName, string $city, string $state): void
    {
    }
}

doctrine_mongodb.yaml

doctrine_mongodb:
    auto_generate_proxy_classes: true
    auto_generate_hydrator_classes: true
    connections:
        default:
            server: '%env(resolve:MONGODB_URL)%'
            options: {}
    default_database: '%env(resolve:MONGODB_DB)%'
    document_managers:
        default:
            auto_mapping: true
            mappings:
                App:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Document'
                    prefix: 'App\Document'
                    alias: App

Это мой services.yaml

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    env(MONGODB_URL): 'mongodb://localhost:27017'
    env(MONGODB_DB): 'tables'

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    App\Repository\:
        resource: '../src/Repository/*'

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

Если запущено команда bin/console debug:container UsersRepository на терминале, возвращается этот ответ:

Information for Service "App\Repository\UsersRepository"
========================================================

 ---------------- ----------------------------------------- 
  Option           Value                                    
 ---------------- ----------------------------------------- 
  Service ID       App\Repository\UsersRepository           
  Class            App\Repository\UsersRepository           
  Tags             doctrine_mongodb.odm.repository_service  
  Public           no                                       
  Synthetic        no                                       
  Lazy             no                                       
  Shared           yes                                      
  Abstract         no                                       
  Autowired        yes                                      
  Autoconfigured   yes                                      
 ---------------- ----------------------------------------- 


 ! [NOTE] The "App\Repository\UsersRepository" service or alias has been removed or inlined when the container was      
 !        compiled.   

Если запущена команда php bin/console doctrine:mapping-info. в терминале, это ответ:

 ! [CAUTION] You do not have any mapped Doctrine ORM entities according to the  
 !           current configuration.                                             
 !                                                                              
 !           If you have entities or mapping files you should check your mapping
 !           configuration for errors.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...