c33s / entity-loader-bundle
将内容存储在PHP文件中,同时保留现有内容,只加载新内容。
Requires
- php: ^7.4.0|^8.0
- c33s/doctrine-extra: *
- doctrine/annotations: ^1.11.1
- doctrine/doctrine-bundle: *
- doctrine/orm: *
- doctrine/persistence: *
- nesbot/carbon: *
- psr/log: *
- symfony/config: ^3.4|^4.0|^5.0
- symfony/console: ^3.4|^4.0|^5.0
- symfony/dependency-injection: ^3.4|^4.0|^5.0
- symfony/event-dispatcher-contracts: *
- symfony/http-kernel: ^3.4|^4.0|^5.0
Requires (Dev)
- codeception/codeception: 4.1.22
- codeception/module-asserts: 1.3.1
- roave/security-advisories: dev-latest
Suggests
- c33s/maker-extra-bundle: contains a maker to create content classes
This package is auto-updated.
Last update: 2024-09-11 02:20:04 UTC
README
结合了 doctrine/doctrine-fixtures-bundle
和 doctrine/doctrine-migrations-bundle
,将内容存储在PHP文件中,同时保留现有内容。类似于 doctrine/doctrine-migrations-bundle
,但提供了对实体管理器的访问。
使用方法
在 src/DataContent
中创建一个PHP文件(您也可以使用 [c33s/maker-extra-bundle
][maker_extra]来自动化此过程),将内容作为实体添加,并在您的symfony项目中运行 php bin/console content:load
来加载内容。
final class Content20210715Example extends BaseContent
{
public static function createdAtDate(): DateTimeImmutable
{
return new DateTimeImmutable('2021-07-09T13:56:39.6982405Z');
}
public function getEntities(): array
{
$entities[] = new NewsEntry('My Headline', 'my content', '2021-07-15');
$entities[] = new NewsEntry('Other Headline', 'my other content', '2021-07-17');
return $entities;
}
}
已加载的内容文件存储在表中,不会再次加载。您还可以实现 preventLoadBeforeDate
和/或 preventLoadAfterDate
来防止在特定日期之前或之后加载。
final class Content20210715Example extends BaseContent
{
//...
public function preventLoadBeforeDate(): DateTimeInterface
{
return new DateTimeImmutable('2021-06-01');
}
public function preventLoadAfterDate(): DateTimeInterface
{
return new DateTimeImmutable('2022-01-01');
}
//...
}
通过命令行选项,您还可以为所有内容文件设置全局的“防止在之前/之后加载”,这可以与 current-date
结合使用以“模拟”当前日期。
您还可以实现 shouldFlushBefore
和 shouldFlushAfter
来强制在内容文件之前/之后刷新实体管理器。
final class Content20210715Example extends BaseContent
{
//...
public function shouldFlushBefore(): bool
{
return false;
}
public function shouldFlushAfter(): bool
{
return false;
}
//...
}
内容加载器在所有加载完成后,在 PreLoadEvent
之前和 PostLoadEvent
之后触发事件。
原因
从需要通过固定值添加/创建内容的需求出发,但允许仅添加内容而不删除或重建现有内容,以便允许应用程序自行添加新内容(例如,添加新文章将自动创建新闻条目)。
可以使用 doctrine/fixtures,但忘记添加 --append
导致数据丢失的风险太高。可以使用 doctrine/migrations,但数据与迁移之间的清晰分离可能很困难。此外,在迁移中使用实体管理器是 不被鼓励 的。
[maker_extra]