Cakephp Fat Models - should I import components?
Let me preface by saying this is the first live cakephp project for me.
I'm trying to move logic out of the开发者_运维技巧 controller to the model but the fact that compoents are not available makes this awkward.
For example, I want to send a notification email after a user registration. I've moved my email function into the model, but now have to import the Email component into the model.
So for the sake of a couple of lines of code (excluding the strings for the message itself) I have to import a component which might already be being used in the controller as well (not in this particular case though).
It seems cake is not really "arranged" for Fat Model concept?
Do not send emails from the model! There's a reason the EmailComponent is a component and not a behavior. Models are about modeling your data. Sending email has nothing to do with data modeling, it's about interacting with the real world, i.e. output, which is why the process is comprised of components and view files.
If something in your MVC structure seems really awkward and weird, you're probably doing it wrong.
The "fat model" concept doesn't mean that all code should be moved to the model, as I'm sure you're already aware. In this case, the Cake team might make the argument--correctly, I think--that sending email is a function of the application logic, not the business logic. If you accept that premise, then any mail or messaging functionality belongs in the controller where components are available.
I always try to think of it like this:
If I were to create an API into my application, I'd want to reuse all of the business logic, but little or none of the application logic. If someone is performing an action against my application via an API, it's (typically, in my experience) not my application's responsibility to send an email directly to the customer. S/He has no idea that s/he is using my app since it's being accessed through an external source. The better solution is to perform the business logic and then, based on it's ability to complete, have your controller (your application logic) send the email.
This won't disambiguate every use case, but it's helped in most of mine.
It's your first project, so don't fret too much about blindly following 'best practices'. Remember that the controller is there for a reason - it's not just the empty filling in a doorstep sandwich.
Once you're up and running, you can review and tweak to your heart's desire and begin to see why you might want to move logic to (or from) the model.
In the broadest sense, the Model is the application's interface with the database. In my opinion, Model output should be data, whether pure (from the database) or modified, and nothing else.
The controller does something with the data.
The view displays the controller's output.
精彩评论