Jump to content

Recommended Posts

Using MVC, the controller does some logic, gets data from the model, and the view presents the content.

 

Where should the reverse be performed?

 

For instance, I have an edit page which is pre-populated with values from the model, and the view changes 1000 to $1,000, 0.4 to 40%, and 2014-10-09 09:31:41 to 10/09/2014 09:31:41 AM.

 

Now I need to save the values, and must convert them back to their original format before doing so.  Should this functionality be performed in the controller, model, or view?

 

Thanks

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/292219-where-is-anti-formatting-performed/
Share on other sites

Short answer - Controller

 

Model = access data

View = presentation layer

Controller = logic that reacts to user activity.

 

long answer - its not really the reverse, 

You are still accessing data

presenting it

and having to react to user activity even if its on the admin side or updating rather than simply displaying.

 

MVC is just a design pattern but it can easily become overwhelming especially when designing small scale sites or sites where only 1 or 2 people are involved in the development.

 

Simply because of following the logic and having multiple files to perform simple tasks (Thats just my opinion)

What 'tryingtolearn' said is true, should be done in the backend.

 

The reason I wanted to make a post is to present the way my MVC application is built, perhaps it sounds like a lot more work, but it's a lot more organized and easier to know where things are done, and why.

 

Frontend

View: Self-explanatory, but associates with Model/Collection, handles what the user can & should see.

Model: Contain data, validation, helperfunctions (Like format a value to money format)

Collection: Same as model, but several.

 

Backend

- Controller: Receive requests, (Only logic here is extracting request data & returning correct response, IE 200)

- Service(s): Handle Logic -- This is where I would, in my application, convert the values back that you mentioned

- Entitiy(ies): Used to handle each model as an object. Getters/setters/validations. Also used for queryBuilding (Insert, update, delete, etc)

- Mapper(s): Handle database operations. (With potential entities)

 

 

Maybe a useless post, but perhaps the design could give you some form of idea. A Controller in my personal view should do nothing but actually handle the request, no actual datahandling or logic in that sense. For me, that's the service & entities job. :)

Short answer - Controller

 

Model = access data

View = presentation layer

Controller = logic that reacts to user activity.

 

long answer - its not really the reverse, 

You are still accessing data

presenting it

and having to react to user activity even if its on the admin side or updating rather than simply displaying.

 

MVC is just a design pattern but it can easily become overwhelming especially when designing small scale sites or sites where only 1 or 2 people are involved in the development.

 

Simply because of following the logic and having multiple files to perform simple tasks (Thats just my opinion)

 

Thanks tryingtolearn,  I agree one could make it overly complicated and in turn overwhelming, however, believe a simple MVC pattern makes life less complicated.  The controller you say...  Is the controller also where validation occurs as they are very similar functions, or is the model also responsible to protect itself before inserting data?  Also, what do you mean by "the admin side"?

 

 

What 'tryingtolearn' said is true, should be done in the backend.

 

The reason I wanted to make a post is to present the way my MVC application is built, perhaps it sounds like a lot more work, but it's a lot more organized and easier to know where things are done, and why.

 

Frontend

View: Self-explanatory, but associates with Model/Collection, handles what the user can & should see.

Model: Contain data, validation, helperfunctions (Like format a value to money format)

Collection: Same as model, but several.

 

Backend

- Controller: Receive requests, (Only logic here is extracting request data & returning correct response, IE 200)

- Service(s): Handle Logic -- This is where I would, in my application, convert the values back that you mentioned

- Entitiy(ies): Used to handle each model as an object. Getters/setters/validations. Also used for queryBuilding (Insert, update, delete, etc)

- Mapper(s): Handle database operations. (With potential entities)

 

 

Maybe a useless post, but perhaps the design could give you some form of idea. A Controller in my personal view should do nothing but actually handle the request, no actual datahandling or logic in that sense. For me, that's the service & entities job. :)

 

Thanks _Alex.  What do you mean by Frontend and Backend?  Is this like client and server?  Are collections, services, entities, and mappers MVC terms or something else?

 

 

Is the controller also where validation occurs as they are very similar functions, or is the model also responsible to protect itself before inserting data?

yes and yes...

If I use a  MVC approach I tend to lean towards the controller being all of my php code and I use stored procedures to move the model functions into the database.

But it really depends on the site design and like I said the size of the project.

Is there a need to keep the sections separate? is it personal preference etc...

 

Honestly the only time I find it "useful" is when there are teams of people working on the development (Designers, coders, think tank idea people)

MVC kinda keeps order to the progress and updates of the site.

 

I actually prefer having things combined and comment the heck out of the page as I go along writing it

 

 

 

 

 

Also, what do you mean by "the admin side"?

I mean the section of the site where administrators can take care of a site, user management, content posting, tracking, etc...

There should be zero business logic in controllers. They are nothing but a very thin layer between http and your domain.

 

Would I be correct in that you don't believe the controller should be responsible to take "formatted" content and bring it back to the format desired by the model (i.e. my original question).  If not, where?

 

Below represents one of my typical controllers.  Seem reasonable?  Don't worry, I won't get upset if you say it isn't :)

class someController
{
    public function saveRecord()
    {
        header('Content-Type: application/json');
        $validate=new validate($someStuff);
        $data=$validate->sanitize($_POST);
        $errors=$validate->validate($data);
        if(empty($errors)) {
            $model=$this->getModel();
            $id=is_null($data['id'])?$model->addRecord($data):$model->updateRecord($data);
            if($id===false) {$errors[]='Unexpected error saving data.';}
        }
        else {$id=false;}
        echo json_encode(array ('errors'=>$errors,'id'=>$id));
    }

    public function display($record_status='active')
    {
        $model=$this->getModel();
        if($data=$model->getData($_GET['id'],$record_status))
        {
            $data=$this->addExtraTwigVariables(array(
                'data'=>$data,
                'contacts'=>$model->getContacts($data['id']),
                'menu_main'=>array('menu'=>$model->getMenu('b_main'),'active'=>ID_com_accounts)
                )
            );
            $this->displayPage($data,dirname(__DIR__).'/templates');
        }
        else {$this->missingPage();}
    }

}
Edited by NotionCommotion

By frontend and backend I do mean client / server. For me, Entities Mappers and Services are a given in an MVC application, but obviously it's just a preference for each developer. I prefer it for the ease, and organizied code. Let me give you an example

 

Controller

 

public function doUpdate() {
$data = $this->request->putJSON();
$myService = new MyService();
$updatedUser = $myService->updateUser($data);
return static::ok($updatedUser);
}

 

Service

 

public function updateUser($data) {
$User = new User($data); //Entity
$User->convertOriginalFormat(); //Just an example function on an Entity, that can do what you wanted to do.
return $this->_myMapper->update($User);
}

 

Mapper

 

public function update(User $user) { //Only accept a User entity
$params = $user->toValidatedArray();
$query = implode(' ', array($this->update, $this->keySearch, $this->returning));
return $this->db->query($query, $params);
}

 

 

So i keep logic in the service. Most often an Entity is able to hold "helper" functions, such as formatting and stuff as well. The Entity can be thought of as the Model in the frontend. Contains data with getters and setters, and helper functions. The mapper can then use an Entity for queryBuilding and creates a proper update Query.

 

I wouldn't advice using this MVC pattern on an existing application because it may be a lot to rebuild, but for a future project, I'd say it's worth giving it a try.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.