Accessing Models Directly Through AJAX I was thinking about how to handle AJAX requests in a MVC environment in PHP in a easy way.

What I've come up is (without showing you the backend code):

$.ajax({
    // url is empty so the request goes to the current route and controller
    // each controller (extended from base controller) checks every request to
    // see if it's an AJAX one. If it is it calls the Model/method specified bellow
    url:'',
    method:'POST',
    data: {
        toCall: 'User@create', // Calls model "User" with method "create"
        args: userData // arguments for method "create"
    },
    success: function(r) {
        // return JSON or true/false
    }
});


So basically the key is this "toCall: 'User@create'" line. which calls models directly. Should that be avoided because of security? Is it possible for a user to somehow change this "User@create" to access other models and methods?

Is my question clear?
Yes this raises concerns

You'll be skipping some controller logic which may involve;


Checking certain user conditions (ie: are they logged-in)
Can they perform this model action due to their ACL/permissions?
Collecting other data from other models/methods to pass into this model method


Depending on your design, accessing a model directly and skipping the controller logic can raise some unexpected errors (described above) and/or give users actions they wouldn't necessarily have. i.e: Admin@RemoveUser

Usually in an MVC pattern, the model and method names are guessable, depending on the action. Ie: http://example.com/user/view/1 = User model, viewAction method. So exposing this information isn't really a concern. What is a concern is users accessing model action that are restricted by controller logic.

So, what should I do?

Contact the controller directly, and have your view processor to detect it's an AJAX request (through the HTTP_X_REQUESTED_WITH=XMLHttpRequest header) to "disable" the default view with all the design, and just passback (usually) a JSON string that you can use with JavaScript (JSON.parse) and do as you want with the result.