如何在自定义的Symfony Bundle中配置Doctrine实体注释自动加载?

3

当我尝试验证我的Symfony模式时,出现以下错误:

[Doctrine\Common\Annotations\AnnotationException]                            
[Semantical Error] The annotation "@Doctrine\Orm\Mapping\Entity" in class C  
hill\EmailUser\Entity\EmailUser does not exist, or could not be auto-loaded 

我看到在这个问题中:Trouble with importing annotations,有人说我们需要从Doctrine简单注释读取器进行更改。虽然在自动加载程序中进行束缚配置似乎很奇怪,但我尝试通过app/autoloader.php进行配置:

use Doctrine\ORM\Configuration;

path = __DIR__."/../vendor/path/to/annotationDriver.php"
Configuration::newDefaultAnnotationDriver(path, false);

我也尝试过搜索,以查找是否存在像这样的参数:

doctrine.orm.mappings.annotations.simple_annotations_reader

我可以将其设置为false,但我找不到任何相关内容。

正如您在下面看到的那样,我也尝试手动将我的bundle映射到config.yml中的ORM设置中。

composer.json:

{
    "name": "root/photoproject",
"license": "proprietary",
"type": "project",
"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"autoload-dev": {
    "files": [
        "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
    ]
},
"require": {
    "php": ">=5.3.9",
    "doctrine/annotations": "^1.4",
    "doctrine/doctrine-bundle": "~1.4",
    "doctrine/migrations": "^1.5",
    "doctrine/orm": "^2.5",
    "incenteev/composer-parameter-handler": "~2.0",
    "sensio/distribution-bundle": "~4.0",
    "sensio/framework-extra-bundle": "^3.0.2",
    "symfony/monolog-bundle": "^3.0.2",
    "symfony/swiftmailer-bundle": "~2.3,>=2.3.10",
    "symfony/symfony": "2.8.*",
    "twig/twig": "^1.0||^2.0"
},
"require-dev": {
    "sensio/generator-bundle": "~3.0",
    "symfony/phpunit-bridge": "~2.7"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
"config": {
    "bin-dir": "bin",
    "sort-packages": true
},
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "web",
    "symfony-assets-install": "relative",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    },
    "branch-alias": null
}
}

app/config/config.yml

imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }

# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices    /configuration.html#application-related-configuration
parameters:
locale: en

    framework:
#esi: ~
#translator: { fallbacks: ['%locale%'] }
secret: '%secret%'
router:
    resource: '%kernel.root_dir%/config/routing.yml'
    strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
serializer: { enable_annotations: true }
templating:
    engines: ['twig']
default_locale: '%locale%'
trusted_hosts: ~
trusted_proxies: ~
session:
    # handler_id set to null will use default session handler from php.ini
    handler_id: ~
fragments: ~
http_method_override: true

    # Twig Configuration
    twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
    # Doctrine Configuration
    doctrine:
dbal:
    driver: pdo_mysql
    host: '%database_host%'
    port: '%database_port%'
    dbname: '%database_name%'
    user: '%database_user%'
    password: '%database_password%'
    charset: UTF8
    # if using pdo_sqlite as your database driver:
    #   1. add the path in parameters.yml
    #     e.g. database_path: '%kernel.root_dir%/data/data.db3'
    #   2. Uncomment database_path in parameters.yml.dist
    #   3. Uncomment next line:
    #path: '%database_path%'

orm:
    auto_generate_proxy_classes: '%kernel.debug%'
    entity_managers:
        default:
            naming_strategy: doctrine.orm.naming_strategy.underscore
            auto_mapping: true
            mappings:
                ChillEmailUserBundle: ~

    # Swiftmailer Configuration
    swiftmailer:
transport: '%mailer_transport%'
hostity/l: { type: memory }

src/Chill/EmailUserBundle/Entity/EmailUser.php

namespace Chill\EmailUser\Entity;

use Doctrine\Orm\Mapping as ORM;
use Symfony\Component\Validator\Contraints as Assert;

/**
 * @ORM\Entity
 */

class EmailUser
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length="1023")
     * @Assert\Email(message="Not a valid email")
     */
    private $email;

    /**
     * @ORM\Column(type="string", length="4096")
     */
    private $password;

    /**
     * @ORM\Column(type="string", length="4096")
     */
    private $salt;

    /**
     * @ORM\ManyToMany(targetEntity="Role")
     */
    private $roles;
}

我的问题是如何在Symfony中实现接受答案所建议的内容(最好保持bundle相对可重用)。

谢谢。


<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

/** @var ClassLoader $loader */
$loader = require __DIR__.'/../vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;                            
1个回答

5
据我所知,您需要为AnnotationRegistry注册加载器。
更详细的文档在这里可用。对于Symfony项目,最简单的方法是使用以下内容的app/autoload
<?php

use Composer\Autoload\ClassLoader;
use Doctrine\Common\Annotations\AnnotationRegistry;

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

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

return $loader;

由于这种需求,捆绑通常使用XML配置容器、路由等。如果您更喜欢注释,并且这是您的私有包,请像上面展示的那样注册加载器。如果您想将其公开,我建议使用XML进行配置。

感谢您的快速回复。我已经更新了我的app/autoload.php并将其附加到问题上,但我仍然看到错误。我想我可能需要切换到XML。 - arthur.00
这就是为什么Doctrine Annotations通过全局注册表使用自己的自动加载机制。如果您想知道注释注册表为什么是全局的,那么没有其他方法可以以简单直接的方式解决自动加载注释类的架构问题。此外,如果您考虑PHP自动加载,那么您会认识到它也是全局的。所以我认为你的答案是正确的,“不要”。我只需要使用XML。 - arthur.00
1
你确定你的 bin/console 使用了 app/autoload 吗?还有一些随机的想法:将 Doctrine\Orm\Mapping 替换为 Doctrine\ORM\Mapping(大小写敏感),清除缓存(可能您的控制台使用 prod 环境并缓存注释)。你如何验证模式? - Mateusz Sip
糟糕,原来是小写的Orm。谢谢。 - arthur.00
发生了,很高兴你度过了那个难关。 - Mateusz Sip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接