Basically I have an html form for inserting a product. The field names, as well as the $_POST vars, are initialized in my Product class. The contructor is "listening" for the submit button. When the user submits the form, the object's state changes to let's say "Ready", which means its attributes are initialized and ready to be inserted into the database.
Then I need to return a message depending on the status of insert (Sucess or Failure), If sucess i'll print something like "Product Inserted Successfully", if it fails: "Null fields detected".
My question is if I'm allowed to put this kind of logic in the view? Like this:
<?php $myproduct = new Product(); ?>
<form>
<!-- Fields -->
</form>
<?php
if ($myproduct->ready()) :
if ($myproduct->insert()) : ?>
<p>Product inserted successfully</p>
<?php
else : ?>
<p>Null fields detected</p>
<?php
endif;
endif; ?>
I really can't think of a simpler way, since I really need to show the message depending on the insert() return status.
So is it allowed in the MVC pattern to mix that kind of logic in the view? I'm not exposing any kind of business logic, just checking the object's status.
No. The domain business logic has no place in the view (nor in the presentation layer as whole). That's why MVC has the model layer.
When you are submitting a form, the order of operations should be as following:
controller receives the request with $_POST
data
controller sends the information to the model layer
controller notifies current view that there was POST
sent
when view is requested to generate response (preferably, not by controller), it sends a Location
HTTP header (to prevent double-posting)
controller receives new request (with only GET
parameter this time)
if required, controller adjusts state of model layer and current view
view inquires model layer whether it contains error state
There would be the order of operations for form submission in Model2 MVC pattern.
Depending on whether you display error messages and/or success messages in the same view as the form itself, the view instance might check the model layer for error state in STEP 4. Then view could decide which Location
header to send.
P.S. The interaction with model layer would most likely happens through service.