Микроядро Symfony 3 и ORM

Я использую Micro Kernel и пытаюсь настроить Doctrine ORM.

приложение/config/config.yml

framework:
    secret: S0ME_SECRET
    templating:
        engines: ['twig']
    profiler: { only_exceptions: false }

doctrine:
    dbal:
        driver:   pdo_mysql
        host:     127.0.0.1
        dbname:   symfony-micro
        user:     root
        password: ''

    orm:

приложение/AppKernel.php

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use Doctrine\Common\Annotations\AnnotationRegistry;


$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

class AppKernel extends Kernel
{
    use MicroKernelTrait;

    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle()
        );

        if ($this->getEnvironment() == 'dev') {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
        }

        return $bundles;
    }

    protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config.yml');

        if (isset($this->bundles['WebProfilerBundle'])) {
            $c->loadFromExtension('web_profiler', array(
                'toolbar' => true,
                'intercept_redirects' => false,
            ));
        }
    }

    protected function configureRoutes(RouteCollectionBuilder $routes)
    {
        if (isset($this->bundles['WebProfilerBundle'])) {
            $routes->import('@WebProfilerBundle/Resources/config/routing/wdt.xml', '/_wdt');
            $routes->import('@WebProfilerBundle/Resources/config/routing/profiler.xml', '/_profiler');
        }

        $routes->import(__DIR__.'/../src/App/Controller/', '/', 'annotation');
    }

    public function getCacheDir()
    {
        return __DIR__.'/../var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return __DIR__.'/../var/logs';
    }
}

источник/приложение/контроллермикроконтроллер.php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use App\Entity\Article;

class MicroController extends Controller
{
    /**
     * @Route("/test/{limit}")
     */
    public function testAction($limit)
    {
        $article = $this->getDoctrine()
        ->getRepository(Article::class)
        ->find(1);

        echo '<pre>';
        print_r($articles);
        die;
    }
}

src/App/Entity/Article.php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Article
 *
 * @ORM\Table(name="article")
 * @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
 */
class Article
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="text")
     */
    private $content;
...

Когда я пытаюсь получить что-то из базы данных, я получаю:

Класс 'App\Entity\Article' was not found in the chain configured namespaces

Я думаю, что проблема в конфигурации ORM. Кто-нибудь может помочь?


person mcek    schedule 10.07.2017    source источник
comment
Можете ли вы показать нам свою часть конфигурации ORM?   -  person yceruto    schedule 10.07.2017
comment
сейчас он пустой, пытался настроить сам, но каждый раз возникала проблема   -  person mcek    schedule 10.07.2017
comment
Вы забыли о директории приложений, но все остальное работает отлично. '%kernel.project_dir%/src/App/Entity' Спасибо!!!   -  person mcek    schedule 10.07.2017
comment
Кстати, следуя новому скелету Symfony github.com/symfony/skeleton/blob /master/composer.json#L23 App — это всего лишь префикс пространства имен ;)   -  person yceruto    schedule 10.07.2017


Ответы (1)


Рекомендуемый способ настройки Doctrine ORM с помощью MicroKernelTrait уже представлен в Рецепт Doctrine из репозитория Symfony:

doctrine:
    # ...
    orm:
        auto_generate_proxy_classes: '%kernel.debug%'
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity\'
                alias: App

Эта конфигурация должна охватывать вашу структуру без пакетов.

person yceruto    schedule 10.07.2017