I'm creating a simple MVC app to learn more about MVC. I have a controller which uses a UserService class to get the desired users:
class UserController extends Controller{
public function Index(){
$data['users'] = UserService::getAll();
$this->view->render($data);
}
public function Add(){
UserService::insert($_POST['username'],$_POST['password']);
}
}
The UserService class uses an ORM (idiorm) to get the data:
class UserService{
public static function getAll(){
return Model::factory('User')->find_many();
}
public static function insert($username,$password){
$user = Model::factory('User')->create();
$user->username = $username;
$user->password = $password; //no good practice in real life offcourse...
return $user->save();
}
}
How do I fit in some validation in here? Like checking if the values aren't empty, that the password matches a certain validation pattern, ...
Should I do something like:
//controller
public function Add(){
if(UserValidationService::checkPassword($_POST['password'])){
UserService::insert($_POST['username'],$_POST['password']);
}else{
//set some errordata and show the view
}
}
Or should I do the validation in the service (model) and return errors?
I'm a little confused on how to put the validation right.
Code update
class UserController extends Controller{
public function Add(){
$result = UserService::insert($_POST['username'],$_POST['password']);
if($result[0]){
//result ok, show view
}else{
//result not ok, pass errors to view
}
}
}
class UserService{
$errors = "";
public static function insert($username,$password){
if(empty($username)){
$errors .= "Please enter a username.";
}
if(empty($password)){
$errors .= "Please enter a password.";
}
if(empty($errors)){
$user = Model::factory('User')->create();
$user->username = $username;
$user->password = $password; //no good practice in real life offcourse...
$user->save();
return array(true,$user);
}else{
return array(false,$errors);
}
}
}