0
votes

I'm trying to find all the users I have in my database and when I'm trying to get the repository, doctrine mapping fails because it can't find what is looking for.

I have this namespace in my project for my code.

composer.json

  "autoload" : {
    "psr-4" : {
      "Olive\\Todo\\" : "src/",
      "Olive\\Todo\\Exceptions\\" : "exceptions/",
      "Olive\\Todo\\Tests\\" : "tests/"
    }
  }

It fails when I'm trying to get the repository to find all the users.

index

/**
 * Get Users array
 *
 * @param EntityManager   $entityManager
 *
 * @return  array
 **/
function findUser( $entityManager )
{
  $ret = [];

  $userRepository = $entityManager->getRepository('User');

  return $ret;
}

This is the error I got when I'm trying to execute this code.

Fatal error: Uncaught Doctrine\Common\Persistence\Mapping\MappingException: Class 'User' does not exist in /srv/www/simple-project/vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:93 Stack trace:

And this is the repository itself.

UserRepository.php

<?php

namespace Olive\Todo\User;

use Doctrine\ORM\EntityRepository;
use Olive\Todo\User\User;

/**
 * @author  Ismael Moral <[email protected]>
 **/
class UserRepository extends EntityRepository
{
  /**
   * Get all users
   *
   * @return  array
   **/
  public function getUser( $maxResults = 50 )
  {
    $dql = "SELECT u FROM user u";

    $query = $this->getEntityManager()->createQuery( $dql );
    $query->setMaxResults( $maxResults );

    return $query->getResult();
  }
}

I think I need to set up some configuration parameters in doctrine in order to load this class.

I import the class at the top of my script, and also I changed the get repository method. And now I have another error.

  $userRepository = $entityManager->getRepository( User::Class ); 

This is the new error I got when I applied the change.


Fatal error: Uncaught BadMethodCallException: Undefined method 'getUser'. The method name must start with either findBy, findOneBy or countBy! in /srv/www/simple-project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:238 Stack trace:

0 /srv/www/simple-project/index.php(78): Doctrine\ORM\EntityRepository->__call('getUser', Array)

1 /srv/www/simple-project/index.php(123): findUser(Object(Doctrine\ORM\EntityManager), Array)

2 {main} thrown in /srv/www/simple-project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php on line 238

Thanks in advance.

1

1 Answers

1
votes

You have to use the namespaced class not the class name. So:

$userRepository = $entityManager->getRepository( 'Olive\Todo\User\User' );

Also you can use this syntax, if the php have 'imported' it via use which i personally use:

$userRepository = $entityManager->getRepository( User::class );