开发者

Where should this code live in MVC structure?

开发者 https://www.devze.com 2023-03-17 13:20 出处:网络
I\'m 开发者_如何学Pythonreading a lot and getting really mixed results. Say I have code like this?

I'm 开发者_如何学Pythonreading a lot and getting really mixed results.

Say I have code like this?

$name = trim($_POST['name']);
$email = trim($_POST['email']);

if(strlen($name) > 0 & strlen($email) > 0)
{
   $u = new User();
   $u.name = $name;
   $u.email = $email;
   $u.validate();
}

Where should this code live? The code that actually checks the form to make sure it has actual values? I say Model, but then what if your form spans across multiple models?

I'm a bit confused and any help to clear it up would be appreciated.


Ideally for the complete separation of concerns:

The Controller should be collecting the $_POST array and passing it to the Model.

Then the model would do the processing such as trim and validating.

I would +1 that the Model contains business logic.


the checks in the model layer should guarantee database integrity. all those checks should live in your u.validate() method.

you may additionally add checks to your controller layer as an optimization or to drive some view action.

i would refactor this way.

controller code

   $u = new User();
   $u.name = $_POST['name'];
   $u.email = $_POST['email'];
   if ($u.validate() && $u.save()) {
       // success code
   } else {
       // fail 
   }

model code

class user {
...
function validate() {
   if (empty($this->name) || strlen($this->name) < 1)  return false;
   if (empty($this->name) || strlen($this-email) < 1)  return false;
}
...


Put this into model section, because model contains business logics..

Reference


This is a great article that goes far to explaining MVC within PHP Oreilly the answers above are correct but in order for you to truly use MVC a certain amount of understanding about why each part goes where it goes is required hopefully this article will push you in the right direction.


If you are validating data before saving (e.g. email, name), then I vote Model.

Your MVC framework should be able to validate each Model's data.

In the end, MVC is an architecture. There is no definitive pattern. So it's up to you. A lot of the time consistency wins out. That is to say, if you want to put it in the controller instead of the model, do it throughout your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消