• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
MVC structural advice - separation of code

#1
[eluser]Lyon[/eluser]
Hi all,

I am new to both codeigniter and the mvc approach to programming and am looking for some guidance on structuring my code. I have read up on the model view controller structure but I am having problems translating what should go where into my own project.

I am creating a small website that will contain my blog, and my portfolio work.

At the moment I have an admin section that manages both.
The admin controller contains the functionality to add a new project, edit an existing project, add a new post to the blog, and edit an existing blog post.

The edit_project_view displays multiple forms on one page, each form covering a different aspect of the project. For example I have a edit name form, edit description, add screenshot, delete screenshot, add video, delete video, edit user guide, edit technologies used in the project etc... all in their own form.

The edit_project function is the biggest function I have. This function is responsible for setting the form validation rules depending on which form has been posted, it is also responsible for passing the information along to the admin_model which is responsible for talking to the database.

Upon a form like add screenshot being posted the function uses the image_lib to watermark and thumbnail the image then pass the filenames along to the admin_model which enters them into the database.


This function is becomming really big and feels poorly structured. I really feel like I need some extra abstraction here.
I think I need to separate the blog and portfolio admin stuff into their own controllers.
I think I might also benefit from a helper somewhere to maybe deal with stuff like processing the images, or entering the data into the database.

I just need help with the structure, like what controllers, models, and helpers should I be using, and what should each one of them contain.
I am not looking for code, just simple comments such as use x controller to do y, and x helper should give the functionality to do z.

If any more information is required (or code posted) please just let me know and I'll try to post it as soon as possible.
Any help/advice would be greatly appreciated.
Thanks in advance!

#2
[eluser]Burak Guzel[/eluser]
I would make every form submit to a separate controller method. You can just set the different destinations in your form_open() calls.

That way you don't have a single function handling all kinds of different form submissions.

#3
[eluser]Lyon[/eluser]
Thanks for the reply.

I am going to make each form post to another area, this will make it so that both the validation and processing is moved out into the main function into smaller easier to manage functions.

I have also moved all of my admin stuff into an admin folder in my controllers giving me the url structure and code structure I wanted. Didn't realise I could just add folders in the controller to give better structure lol.

I have also moved my blog and projects admin into separate controllers.

Thanks again.

Oh, and I like your website, some really nice tutorials on there. I especially liked the one on creating more readable code.

#4
[eluser]Lyon[/eluser]
One more thing, I guess it falls into the same kind of category.

Say I am using object(classes) for my databases, like say I have a Project class that holds the name, description, etc...

Where would I create this class?

At the moment it is in a separate classes folder under applications and I am using require_once in the files that need it, however it is needed in the model, controller, and view files.

The class has absolutely no functionality and is just a preferred way of accessing the data over using arrays.

Where should classes like this be situated and how should they be included/loaded?

Thanks again.

BTW . I am getting the objects from the db queries using :
Code:
$previews = array();
while($preview = mysql_fetch_object($query->result_id, 'Project_preview'))
{
    array_push($previews, $preview);
}
return $previews;

#5
[eluser]Myles Wakeham[/eluser]
Hi Lyon,

Think of it this way....

M (Model) = The representation of persistent data to your application. Although many will simply say this is the place where you put all of your database queries, SQL, etc. its really more than that. Its where you reference the business objects that your application works on, and includes transforms, etc. to those objects. So in direct response to your question, your 'Project' class is defined in the Model, along with its Get/Set methods, properties, save/load/delete logic, etc. And you would want to do this in such a way that it works to your business requirements (ie. if you ever plan on changing out the type of database you are storing persistent data in, then code it accordingly in the model - ie. MySQL vs. PostgreSQL, Firebird, etc.).

V (View) = The template layer for content. This is like a Smarty template if you are familiar with those. Its an abstraction of the web pages to be displayed but supports template logic.

C (Controller) = The API/Interface code. This is where all user or system events come into your system, are processed and dispatched accordingly. Think of it like a Butler at a restaraunt. You order to the kitchen for your food, but your entire interface to the cooks is through a Butler. The Controller acts in this capacity regardless of what type of interface you are working with (ie. HTML page, AJAX request, etc.). The controller polices the business and security rules on your behalf before allowing your request to hit the Models that do the transforms, etc.

--
I hope this helps clear up where things go for you. Good luck!

Myles

#6
[eluser]Lyon[/eluser]
Thanks, I think I get it now.

I have decided to put my classes such as Project_Preview, Project etc... all in a helper file and just load the helper where it is needed. I have the logic for getting/setting/deleting all of the entries defined as methods in the model.

The classes aren't really classes, more just structures that hold the data to be able to pass between functions, they have no methods and only public variables, so I feel they fall more under the helper category.

Also this way I could change the database used in the model and as long as it still returned the structure classes defined in the helper file nothing would break and no code outside the model would need to be changed.

Thanks again.

#7
[eluser]Myles Wakeham[/eluser]
But what you are attempting to do with a 'helper' file is precisely what the Model class is designed to do. Its your object representation of the data.

For example, let's say you need to create a new Project. You just load the model and instantiate a new object from it. Then set its properties, and call its save() function. Done. You can use this anywhere in your app. Same is true for loading, deleting, checking project expiration status, whatever. They are just functions of the class.

I guess I don't get why you are choosing helper functions for this. They are better used for general utility functions that don't deal with 'business data' as a model would. It would seem to me that the representation of data for a Project, etc. would be exactly that - important business data representing an object view of a persistently stored record. Its what a Model was designed to be used for.

Myles

#8
[eluser]Lyon[/eluser]
Sorry, I had to abandon the project for a while while I got another project sorted.
I could have sworn I replied to this :-S my bad :red:

I think what you were meaning was something like :
Code:
$user = new User();
$user->username = "my_username";
$user->password = "my_password";
$user->Save();

I'm not really sure how that would work though.
Would it be something like :
Code:
class User
{
    private $db = null;
    private $CI = null;

    public $username = '';
    public $password = '';
    public $id = -1;

    public function __construct()
    {
        $this->CI &= get_instance();
        $this->db = $this->CI->load->database('user', true);
    }

    public function save()
    {
        $this->db->insert('users', array("username" => $username, "password" => $password));
        $this->id = $this->CI->insert_id();
    }

    public function get_from_username($username)
    {
        $this->db->from('users');
        $this->db->where("username", $username);
        $query = $this->db->get();

        if($query->num_rows() !== 1) return false;

        $row = $query->row();
        $this->username = $row->username;
        $this->password = $row->password;
        $this->id = $row->id;
    }
}

Or would it be different, there seem to be a lot of CRUD tutorials on the internet, but apart from using Doctrine I cannot find any using objects, just arrays of information passed to a model.

Or should I just use Doctrine for CRUD?

Thanks.

#9
[eluser]Yanny[/eluser]
I'm also new to MVC and CodeIgniter. What I have learned is:

Views: put all kind of visual things, like forms, confirmation pages, error pages etc...

Models: put all things which requires database connection, like sql queries, functions like get_users(), get_user($id) etc...

Controllers: put if and else statements, calls to models' functions, display views.

#10
[eluser]WanWizard[/eluser]
[quote author="Lyon" date="1279818598"]I think what you were meaning was something like :
Code:
$user = new User();
$user->username = "my_username";
$user->password = "my_password";
$user->Save();
[/quote]
That is exactly how an ORM works, so no need to develop that yourself, there are plenty of ORM implementations around.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.