从自定义捆绑包加载夹具

Load fixtures from custom bundle

提问人:H3lltronik 提问时间:12/4/2019 最后编辑:yiviH3lltronik 更新时间:12/4/2019 访问量:660

问:

我正在为 Symfony 构建一个简单的捆绑包,我想知道我是否可以运行位于其中的固定装置,因为它不在项目根文件夹中。 这是我的项目结构:src

Project
|
+--AdminBundle <- My custom bundle
|  +--Controller
|  +--DataFixtures
|  |  |
|  |  +--AdminFixtures.php <- The fixtures I want to run
|  | 
|  +--DependencyInjection
|  +--Entity
|  +--Resources
|
+--assets
+--bin
+--config
+--public
+--src
+--templates
+--vendor

这是 AdminFixtures 的代码.php


namespace ExampleVendor\AdminBundle\DataFixtures;

use App\AdminBundle\Entity\User;
use App\AdminBundle\Entity\Profile;
use Doctrine\Bundle\FixturesBundle\Fixture;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Bundle\FixturesBundle\ORMFixtureInterface;
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class AdminFixtures extends Fixture implements FixtureGroupInterface {
    private $passwordEncoder;


    public function __construct(UserPasswordEncoderInterface $passwordEncoder) {
        $this->passwordEncoder = $passwordEncoder;
    }

    public function load(ObjectManager $manager) {
        // Fixtures stuff
    }

    /**
     * This method must return an array of groups
     * on which the implementing class belongs to
     *
     * @return string[]
     */
    public static function getGroups(): array {
        return ['admin'];
    }
}

当我运行时,我收到一个错误,说:php bin/console doctrine:fixtures:load

[错误]找不到任何要加载的夹具服务。

我读到一些东西,每个实现的类都会自动注册为固定装置,但我认为这是行不通的,因为我在这里寻求帮助。FixtureGroupInterface

如何手动将其注册为夹具?如何使命令起作用??php bin/console doctrine:fixtures:load

PHP symfony 学说-orm symfony4

评论


答:

1赞 Yoann MIR 12/4/2019 #1

我不太了解 DoctrineFixtures 捆绑包,所以每个实现某个接口的加载类最终都可能被使用,但我想这只有在你确保加载了 src 目录之外的类时才有可能,看看你的composer.json它应该包含类似的东西:

................
    "autoload": {
        "psr-4": {
            "": "src/",
        }
    },

并考虑添加类似的东西: (假设您在 AdminBundle 中使用“Admin\”作为类的命名空间)

................
    "autoload": {
        "psr-4": {
            "": "src/",
            "Admin\\": "AdminBundle/",
        }
    },

另外,了解symfony的人最终会纠正我,但我不确定你是否应该再创建这样的捆绑包了。要么 Admin 是您应用程序的一个模块,您将其放在 src/Admin 中,要么您考虑在其他地方重用它并将其作为适当的库放在您的供应商中?

评论

0赞 H3lltronik 12/4/2019
是的,它将是一个可重用的捆绑包,通过 composer 从 git 存储库安装,某些项目可能拥有它,需要数据库交互的项目,现在它在根文件夹中进行开发,完成后我会将其上传到存储库,然后将其安装为供应商包。关于 psr-4 命名空间,我已经这样做了,所以我能够在我的项目中使用我的捆绑包中的类,但我无法使用 fixtures 命令从那里加载夹具
1赞 Yoann MIR 12/5/2019
是否必须在服务声明中设置标签?关于在供应商目录中处理您的捆绑包,这里有一些提示:carlosbuenosvinos.com/... & medium.com/pvtl/local-composer-package-development-47ac5c0e5bb4
2赞 Yoann MIR 12/5/2019
也可能与您的问题有关:stackoverflow.com/questions/50984433/...