mardi 29 mars 2016

MVC pattern with AJAX calls

this is a weird question about a php mvc pattern with ajax calls, the purpose is make a better and dynamically web apps let me explain you:

when i learn php i used this pattern specifically :

model.php

<?php
class myClass {

    private $attrOne;
    private $attrTwo;

    public function getAttrOne() {
        return $this->attrOne;
    }

    public function setAttrOne($attrOne) {
        $this->attrOne = $attrOne;
    }

    public function getAttrTwo() {
        return $this->attrTwo;
    }

    public function setAttrTwo($attrTwo) {
        $this->attrTwo = $attrTwo;
    }

    // ----------------------------------------------------

    public function doSelect() {
        //some code
    }

    public function doInsert() {
        //some code
    }

    public function doUpdate() {
        //some code
    }

    public function doDelete() {
        //some code
    }

}

controller.php

<?php

require "../models/model.php";

if(isset($_POST['action'])) {
    $action = $_POST['action'];
    if(is_callable($action)) {
        $action();
    }
}

function registerSomething(){
    $model = new myClass();
    $model->setAttrOne($_POST['attrOne']);
    $model->setAttrTwo($_POST['attrTwo']);
    $return = $model->doInsert();
    echo $return;
}

function registerSomething2(){
    // more app logic code and other stuff
}

view.php -> this is most a pure html file with php extension

<div id="result"></div>
<form id="register" role="form" >
    <input type="text" id="attrOne" name="attrOne"/>
    <input type="text" id="attrTwo" name="attrTwo"/>
</form>

<script src="script.js" type="text/javascript"></script>

And the script.JS

$('#register').submit(function() {
    var action = 'registerSomething';
    $.ajax({
    data: $(this).serialize() + '&action='+action,
    url: '../controlllers/controller.php',
    type: 'POST',
    success: function(response) {
            $('#result').html(response);
        }
    })
    return false;
})

so, what do you think about this pattern, is this pattern efficient? what is the best way to do ajax calls with a proper mvc pattern in php? is this a best practice?

i hope you can answer :)

thank you!

Aucun commentaire:

Enregistrer un commentaire