Отображение сущностей не работает

Я пытаюсь использовать Doctrine2 с ZF3. Все компоненты были установлены с помощью composer.

Когда я пытаюсь использовать Entity, у меня есть исключение:

Doctrine\Common\Persistence\Mapping\MappingException

Класс Application\Entity\Concours не существует

Исключение возникает, когда я использую в действии контроллера:

$concours = $this->entityManager->getRepository(Concours::class);

У меня такая же проблема, если я использую:

$entity = new Concours();

or

$entity = new \Application\Entity\Concours();

Я действительно не понимаю, почему...

Спасибо за помощь...

Моя конфигурация:

config/local.php

use Doctrine\DBAL\Driver\PDOMySql\Driver as PDOMySqlDriver;
return [
    'doctrine' => [
        'connection' => [
            'orm_default' => [
                'driverClass' => PDOMySqlDriver::class,
                'params' => [
                    'host'     => '127.0.0.1',                    
                    'user'     => 'xxxx',
                    'password' => 'xxxx',
                    'dbname'   => 'goch',
                ],
            ],            
        ],        
    ],
];

config/modules.config.php

return [
    'Zend\Cache',
    'Zend\Form',
    'Zend\InputFilter',
    'Zend\Filter',
    'Zend\Paginator',
    'Zend\Hydrator',
    'Zend\Router',
    'Zend\Validator',
    'DoctrineModule',
    'DoctrineORMModule',
    'Application',
];

Для прикладного модуля,

модуль/приложение/config/module.config.php

namespace Application;

use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;


return [
    'router' => [
        'routes' => [
            'home' => [
                'type' => Literal::class,
                'options' => [
                    'route'    => '/',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
            'application' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/application[/:action]',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\IndexController::class =>  Controller\Factory\IndexControllerFactory::class,
        ],
    ],
    'view_manager' => [
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
    ],

  'doctrine' => [
        'driver' => [
            __NAMESPACE__ . '_driver' => [
                'class' => AnnotationDriver::class,
                'cache' => 'array',
                'paths' => [__DIR__ . '/../src/Entity']
            ],
            'orm_default' => [
                'drivers' => [
                    __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
                ]
            ]
        ]
    ]  
];

Мой контроллер (module/Application/src/Controller/IndexController.php):

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Doctrine\ORM\EntityManager;
use Application\Entity\Concours;

class IndexController extends AbstractActionController {

     /**
   * Entity manager.
   * @var Doctrine\ORM\EntityManager
   */
  private $entityManager;

  // Constructor method is used to inject dependencies to the controller.
  public function __construct($entityManager) 
  {
    $this->entityManager = $entityManager;
  }


    public function indexAction() {
        return new ViewModel();
    }


    public function concoursAction(){
        $concours=array();

$concours = $this->entityManager->getRepository(Concours::class);
    // Render the view template
    return new ViewModel([
      'concours' => $concours
    ]);        

    }
}

И связанная фабрика

namespace Application\Controller\Factory;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\Controller\IndexController;

/**
 * This is the factory for IndexController. Its purpose is to instantiate the
 * controller.
 */
class IndexControllerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, 
                     $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');

        // Instantiate the controller and inject dependencies
        return new IndexController($entityManager);
    }
}

Все мои файлы классов сущностей находятся в module/Application/src/Application/Entity/, вот класс сущностей Concours:

<?php

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Concours
 *
 * @ORM\Table(name="Concours", uniqueConstraints={@ORM\UniqueConstraint(name="numero_UNIQUE", columns={"numero"})})
 * @ORM\Entity
 */
class Concours
{
    /**
     * @var integer
     *
     * @ORM\Column(name="ref", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $ref;
...
}

person greg f    schedule 23.03.2017    source источник


Ответы (1)


Вот ваша проблема:

Все мои файлы классов Entities находятся в модуле/Application/src/Application/Entity/

Zend 3 использует PSR-4 вместо PSR-0, который считается устаревшим. Вы можете подтвердить это, проверив composer.json файл. Вы должны увидеть следующее объявление:

"autoload": {
    "psr-4": {
        "Application\\": "module/Application/src/",
    }
},

В PSR-0, если вы определите, что Foo\Bar пространство имен закреплено в src/, он будет искать класс в src/Foo/Bar/{your_class}.php, а в PSR-4 он будет искать в src/{your_class}.php.

Итак... чтобы решить вашу проблему. Переместить объект Concours из:

модуль/приложение/SRC/приложение/сущность/

to:

модуль/приложение/SRC/сущность/

person SzymonM    schedule 24.03.2017