Logic in the model or in the controller with CodeIgniter?

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

I have an application that is registering. Users Currently, the stream is as follows:

  • The user goes to "someebpage / register", which loads the controller's register function
  • The controller checks whether the form is submitted - if it is not, show them the form, otherwise call the "register" function of the "users" model
  • The user models the validation to ensure that the username is already completed. If so, it returns an error code (defined as a PHP constant) for this error.
  • If the username has not yet been accepted, the model registers the user and returns TRUE.
  • The controller collects what the model register function returns and displays an error page, success page, or database failure page based on the error code.

As you can see, I tried to move the logic as much as possible into the model. The only logic I couldn’t get around with was to validate the form, since it seems that CodeIgniter is forcing you to put it in the controller. (If no one knows how to do this)

Should I develop like this with CodeIgniter or with MVC in general?

Thanks in advance for your help.

+4
source share
1 answer

As you will find, CI is flexible and allows you to organize things in several ways. I feel that models should only be reserved for functions that communicate directly with your db. I do not use them for general logic. However, I understand why you also do not want to fill logic with logic. My solution is to create your own libraries to contain the logic you invoke from the controller. Here is information on how to create your own library here: http://codeigniter.com/user_guide/general/creating_libraries.html

To authenticate users, I create a library called auth_library.php, which contains the functions used by the login, registration, etc. controllers. Similarly, you can create auth_model that contains functions that connect to db.

You may also be interested in this series of guides: http://www.phpandstuff.com/articles/codeigniter-doctrine-from-scratch-day-1-install-and-setup The author will guide you through the doctrine plugin with CI, which puts an abstraction layer between your models and db. This is very interesting, brilliantly explained, and uses the registration / login system for the original examples.

+6
source

Source: https://habr.com/ru/post/1314901/


All Articles