views:

34

answers:

1

Hi!

I'm relatively new to CodeIgniter and the MVC philosophy in general, so I'm trying to clarify this before I make any bad habits.

I have an application that registers. Users. Currently, the flow is like this:

  1. User navigates to the "somewebpage/register", which loads the "register" function of the controller
  2. Controller checks to see if the form is submitted - if it was not, show them the form, otherwise, call the "register" function of the "users" model
  3. Users model checks to see if the username is already taken. If it is, it returns an errorcode (defined as a PHP constant) for that error.
  4. If the username wasn't already taken, the model registers the user and returns TRUE.
  5. Controller collects what the "register" function of the model returns and shows an error page, a success page, or a database failure page based on the errorcode.

As you can see, I tried to move as much logic as possible into the model. The only logic that I wasn't able to relocate was that of the form validation, as CodeIgniter seems to force you to put it into the Controller. (Unless anyone knows a way around this)

Is this the way I should be developing with CodeIgniter, or with MVC in general?

Thanks in advance for any help.

+2  A: 

As you'll have discovered CI is flexible and allows you to organise things in several different ways. My feeling is that Models should be reserved only for functions that directly communicate with your db. I don't use them for general logic. I understand however why you don't want to fill up you controllers with logic either. My solution is to create your own libraries to contain logic which you then call from the controller. There's information on how to create your own library here: http://codeigniter.com/user_guide/general/creating_libraries.html

For user authentication I create a library called auth_library.php which contained functions used by login, register etc controllers. In the same way you can create an auth_model which contains the functions that connect with the db.

You might also be interested in this series of tutorials: http://www.phpandstuff.com/articles/codeigniter-doctrine-from-scratch-day-1-install-and-setup The author takes you through using the doctrine plugin with CI which puts an abstraction layer between your models and the db. It's very interesting, brilliantly explained and uses a sign up/login system for initial examples.

musoNic80
The Model in MVC is suppose to have the logic as it is the domain model, but there is nothing preventing you to break it into different layers.
airmanx86
Thank you for your help, musoNic80 and airmanx86! You guys clarified this confusing question.I was getting kind of worried - no one was answering. ;)Thanks!
Jonathan Chan