質問

For a long time I have been using ActiveRecord-like approach for database entities (static classes retrieve rows from DB and instantiate the entity). I know it violates the single responsibility principle, but it somewhat seems more human to me. After reading a lot of articles how bad the AR is, I am trying to "get a data mapper mindset", but I am failing.

I am experimenting with Doctrine 2 in Symfony. I understand the separation of Repositories (they retrieve data from db) and Entities (they hold the data). What I don't know is, where am I supposed to place the process of saving uploaded file.

Let's say I have User entity and every user can save his photo. This photo's path should be stored in the entity, that's clear. But where do I define the path? And what object should save the uploaded photo to the target path?

I have seen the Symfony docs on this topic. They generate the URL within Entity object, but isn't this also violating the single responsibility principle? Why does entity (which only holds data) generate a path on filesystem (even relative)?

This bothers me a lot. I can't get the right mindset to be able to see the advantages of DM as it brings to me a lot of complications.

役に立ちましたか?

解決

You're correct - the example in the symfony docs violates the SR principle.

A cleaner way of handling uploads would be creating a doctrine listener/subscriber that is responsible for handling this process outside of your entity.

A very nice implementation is the VichUploaderBundle.

It can be configured using annotations or YAML ...

... provides (optional) integration with the filesystem abstraction library Gaufrette by KnpLabs ...

... and is pretty easy to set up.

I definitely recommend giving it a try or browse the source if you're looking for an implementation example.

他のヒント

think its hard to really solve such a problem.

here are 2 dirrent approaches i like.

  1. the repository / entity shouldnt care about uploading, just write a service that is responsible for this task and persist "something (custom type? or string, ...)" that represents the uploaded file.

  2. write an event listener that cares about uploading. there is an ugly implementation in the symfony documentation doing this.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top