Search code examples
phpmodel-view-controllerformscontrollers

Best practise for handling form submission in controllers


Lets say for example I am creating a an online shop. I have a controller called products and within that controller I have a function called create_product. Create_product calls a view that displays a form where users get to enter new products into the database.

When the user fills in the form to create a product, should I send the action back to the create_product controller and handle it with an IF statement? or offload to another function?

Example

<form method="post" action="www.example.dev/products/create_product/add"> 
//the above form would post back to the original controller

function create_product()
{
    if(uri->segment(3) == "add")
    {
        //call a model to do all the database stuff
    }

    load->view->create_product_form;
}

Is this the best way to handle this or should I be passing it off to another function?


Solution

  • Don't cram a ton of stuff in one function using the URI segment to filter it. createProduct() can list the products available for creation (in a CRUD format, I assume), and the submission of the form should ping another controller with the POSTed data. Perhaps insertProduct(), where the data is sanitized and sent to the model for insertion to the database.

    Separation of concerns! Keep the functions as separate as possible with good descriptors for the names of the functions.