PHP MVC – Using AJAX in PHP MVC Controllers

ajaxmvcobject-orientedPHP

I'm learning to use the MVC pattern to design my PHP's software. I always use ajax to send requests to my controllers so often I've a code structure like this:

<?php
if(isset($_POST['action']) && $_POST['action'] == 'something'){
// code goes here
}
?>

I've readed various articles about the MVC pattern and all seems to use controllers that are objects who will interact with the view. I've a strange concept of the view when i design them, I prefer to create standard html markup and if needed I include some php object to interact with the related data extracted from the database, this because i try to integrate jQuery ajax in almost all the parts of my projects. Is this approach wrong, so i need to switch off ajax, to use only php and oop?

Best Answer

PHP allows for mixing server side code and client side code. Both can coexist in the same file. This is the root of your misunderstanding of the MVC pattern.

By putting the server side logic in the same file as the client side logic (the jQuery API calls) you are not properly separating your concerns. Separation of Concerns is the central concept behind the Model-View-Controller pattern.

From Design Patterns - MVC Pattern: (emphasis, mine)

MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.

  • Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.

  • View - View represents the visualization of the data that model contains.

  • Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.

There are use cases for putting server side and client side code in the same file in PHP. If you've got a simple script that lives on its own and is not a part of something bigger then this programming strategy can be OK.

This is also why PHP got a bad name, but that is a discussion WAY beyond this post.

Your coding style is not MVC. Depending on what you are building, this can be OK.

If you do want to adhere to MVC you can still use AJAX. The URL that responds to the AJAX call is just another controller, that renders another view.

AJAX and MVC play very well together.