简体   繁体   English

Symfony2 / Doctrine:如何从实体类持久化一个实体?

[英]Symfony2/Doctrine: How to persist an entity from the entity class?

Short Description of the problem: I generate a file inside the entity class and would like to save the filename to the database. 问题的简短描述:我在实体类中生成一个文件,并希望将文件名保存到数据库中。 The controller doesn't know about this (wheter or not the filename has changed, so it's not practical to persist from the controller. 控制器对此一无所知(无论文件名是否更改,因此从控制器持久保存都不可行。

Is there a way for an Entity to persist itself? 实体是否可以保持自身状态?

Example of my use: The entity class is for an image in a gallery. 我的使用示例:实体类用于画廊中的图像。 I always keep the original file and work with a cached version of the file. 我总是保留原始文件并使用该文件的缓存版本。 When the image is changed (rotated for example), the cached version is deleted. 更改图像(例如旋转图像)时,将删除缓存的版本。 The cached version also be deleted in other cases. 在其他情况下,也将删除缓存的版本。 When the file is needed, I check if the cached file exists, otherwise it is regenerated with a new filename from the archived image. 当需要该文件时,我检查缓存的文件是否存在,否则将使用存档映像中的新文件名重新生成该文件。 I need a new filename because that resets the cache for various thumbnail sizes. 我需要一个新的文件名,因为这会为各种缩略图大小重置缓存。

When I generate that new file, I have to save its filename to the database somehow. 生成新文件时,必须以某种方式将其文件名保存到数据库中。 Because it is only decided in the Entity when to regenerate the image, it would be practical if the entity could persist itself to the database, but I haven't found a solution for that. 因为仅在实体中决定何时重新生成图像,所以如果实体可以将自身持久保存到数据库中将是可行的,但是我还没有找到解决方案。

Is there a way to do this or is there a whole different concept I should be using to regenerate the image file? 有没有办法做到这一点,或者我应该使用一个完全不同的概念来重新生成图像文件?

Entities in Doctrine are not active records - they cannot perform persistance actions by themselves, so they rely on a Big Brother [the entity manager]. Doctrine中的实体不是活动记录 -它们本身无法执行持久性操作,因此它们依赖于Big Brother [实体管理器]。

Even if the controller doesn't know wether any filename as changed or not, you do - just persist your picture every time: if nothing changed, Doctrine won't touch the entity. 即使控制器不知道是否更改了任何文件名, 可以这样做-每次都保留您的图片:如果没有更改,Doctrine将不会碰到实体。

Have a look at lifecycle events too, maybe you can find useful to fire a @PreUpdate method before persistance [eg generating thumbnails]. 也可以看看生命周期事件 ,也许您会发现在持久化之前激发@PreUpdate方法很有用(例如,生成缩略图)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM