Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

php - Symfony2 MVC: where does my code belong?

I'm seeking clarification on whether to put code in a controller, an entity or to make a service.

I have 'cardset' and 'card' objects (where many of the latter are embedded in the former, MongoDB), represented by normal PHP classes/objects. These contain attributes e.g. 'id', 'postal_address'.

I have a method that generates a PDF of a card. Currently I have that inside the 'Card' object so from a Controller I can call:

$card->makePDF()

That seems clean and OO to me, but I suspect I'm wrong.

If I put all the logic in the controller that gets long and unwieldy, and I'm not sure the controller is the place for methods that act on my objects. Is that what services are for?

To try and summarise: should an object know all the regular things it could do 'to itself' and have them inside as member functions, or should methods elsewhere be passed the object to act upon. If so, where should those methods be kept?

I'm pretty sure it's not a 'Repository' because that just seems to help retrieve/store entities.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer:

PDF generation should be a service, not a method on an object.

Longer answer:

In general, and in Symfony2 especially, models should just be used to store data. Controllers are used to manipulate relationships between models, and Views are used to express the data in human- or computer-readable form. Services are for things that don't really fit into any of the above -- things that don't have to do with your web application's state.

A good example is sending emails. Emails contain data (model). Users have sent Emails (controller). Emails look a certain way (view). However, the act of actually sending emails is independent of the web application's state (all the service knows is it was asked to send this email to these people). Thus, it makes sense that there is an independent service that just handles sending emails.

Similarly, the act of generating PDF files is independent of the state of the web application. A PDF generator doesn't need to know about what's going on in your app, it just knows it was asked to make a PDF.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...