Patrick
Patrick

Reputation: 1275

MVC best practice when adding functions to controller?

I'm writing a function in my controller; this is supposed to take in a form, process it, register the user in DB, send a confirmation email etc etc.

to avoid this function to be too cluttered, I was thinking of calling some sub-functions (eg:

function registration()
{
  //process form..

  _insertInDb($formdata)

  _send_mail($address);

  //load confirmation view..
}

function _send_mail($to)
{
  //code here
}

function _insertInDb($formdata)
{
  //other code here...
}

I'm not sure whether writing all the functions in the controller would be best practice -maybe I should insert all 'supporting' function (eg send_mail and insertInDb in this example) in another file and then import them?

This would probably make the controller much more readable.. what's your view?

Upvotes: 3

Views: 2692

Answers (3)

Daniel Elliott
Daniel Elliott

Reputation: 22867

SOLID's 'S' - Single Responsibility Principle

Move functions to their own class(es) that are responisble for mailing, database inserts etc.

Upvotes: 0

Dhanasekar Murugesan
Dhanasekar Murugesan

Reputation: 3239

I assume you would use apt layers to handle each step in the process of registration.

  1. Process user request
  2. Validate and register
  3. Send out a confirmation notification on successful completion.

From Controller:


  1. ProcessRequest() - transforms the user form into User Entity to be understandable by the business layer(say UserService)
  2. Registeruser() - takes in User entity returned by ProcessRequest() and Send this to UserService()
  3. based on notification from UserService() , SendNotification() process further

From Business layer: ( UserService)


  1. RegisterUser() - internally calls its own method 'ValidateUser()' to validation user information
  2. If its succeeded, it requests DataAccessLayer (say UserDAL) to Save it to Database
  3. If not, then sends an error specifically on what grounds it has been failed.

I assure that it provides what you have expected. Correct me if I am wrong..

Welcome with regards...

Upvotes: 1

Nate
Nate

Reputation: 30646

MVC is simply a presentation pattern, all of your "business logic" should reside outside of your "MVC" code. Your app should function exactly the same of all of MVC code went away and was replaced with something else.

I'd make a separate class, and have the controller invoke an instance of that class, which will make the necessary DB Inserts, send email alerts, do logging, etc.

update

Since CodeIgniter appears to be a php based CMS, I'd recommend starting here for indepth detail -- http://php.net/manual/en/language.oop5.php

Code like this should get you moving the right direction:

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?> 

Upvotes: 2

Related Questions