javascript - Using JS OOP with PHP

509

I'm new at JS programming. I have to write a php webapplication which uses ajax calls for every action (can't reload the page). So I have the php code done, and the JS as well, but I don't know what does JS OOP mean. I did google search for hours, and all I could figure out was "JS has no classm but there are tricks". So I would like to ask you to lead me to the right way and show me how to make it right.

I have four js files:

content.js, function.js, onload.js and validate.js

For now, I only do care about the function.js. It has code only for the ajax calls. Their names are:

NewMember(), SearchMembers(), ShowDetails(), DeleteMembers() and EditMember()

I'm going to show you only the first function (I don't want to waste your time by duplicating since each function is totally similar)

function NewMember() {

    if (checkFields() == true) {
        Loading("start");
        var dataArray = {
                        first_name  : $('#first_name').val(),
                        last_name   : $('#last_name').val(),
                        birth_date  : $('#birth_date').val(),
                        home_phone  : $('#home_phone').val(),
                        work_phone  : $('#work_phone').val(),
                        email       : $('#email').val(),
                        email_again : $('#email_again').val(),
                        country     : $('#country').val(),
                        city        : $('#city').val(),
                        address     : $('#address').val(),
                        comment     : $('#comment').val()     
                    };

         var JSONString = JSON.stringify(dataArray);

         $.ajax({
              type: 'POST',             
              url : 'adapter.php',
              data: {
                  data      : JSONString, 
                  action    : 'create' },
              success: function(msg) {
                  alert(msg);
                  resetFieldValues();
                  SearchMembers();
              },
              error: function() { 
                  alert("Oops! Something went wrong, please reload the page!");
              }    
        }); 
    }
}

My question is, how would you re-write this by using the JS OOP? Full code is not neccessary, but please give me "easy" answers since I'm really a newbie. I'm really confused :/ Thanks for your help!

486

Answer

Solution:

JavaScript is a completely object-oriented language.

Instead of the Classical Inheritance model that programmers are usually familiar with, JavaScript has a unique take on things with its model of Prototypical Inheritance.

Consider classical inheritance in PHP:

<?php
class Arachnid {
  public $legs = 8;
  function crawl(){ /***/ }
}
class Spider extends Arachnid {
  function creep(){ /***/ }
}
class OrbSpider extends Spider {
  function buildBeautifulWeb(){ /***/ }
}
?>

This is arguably the simplest methodology in JavaScript for the same faculty:

function Arachnid () {}
Arachnid.prototype.legs = 8;
Arachnid.prototype.crawl = function () { return "crawling" };

function Spider () { /* this is a constructor, so don't define spider's methods in here -- they'd be redefined for every constructor call (each instance) */ }
Spider.prototype = new Arachnid(); // Spider inherits from a new basic Arachnid
Spider.prototype.constructor = Spider;
Spider.prototype.creep = function () { return "creeping" }; // Attach Spider's methods to its prototype for best performance

function OrbSpider () {}
OrbSpider.prototype = new Spider(); // we wholly overwrite the natural prototype to a basic arachnid
OrbSpider.prototype.constructor = OrbSpider; // so we must replace the constructor for instanceof to work
OrbSpider.prototype.buildBeautifulWeb = function () { return "webbing" };

// Testing
var orb = new OrbSpider();

console.log( orb.buildBeautifulWeb() ); //>> webbing
console.log( orb.creep() ); //>> creeping
console.log( orb.crawl() ); //>> crawling
console.log( orb.legs );    //>> 8

console.log( orb instanceof OrbSpider ); //>> true
console.log( orb instanceof Spider);     //>> true
console.log( orb instanceof Arachnid);   //>> true

In JavaScript, you create Prototype Chains. When you ask an object for a property, JavaScript will first check the object itself for that property -- if it isn't found, JavaScript will check the object's prototype object. If the property isn't there either, JavaScript will check that prototype object's own prototype -- and so on, and so forth, bubbling up the Prototype Chain until the property is found (or not).

368

Answer

Solution:

JS means JavaScript. OOP means Object Oriented Programming. This is programming JavaScript in an OOP manner. It doesn't have a formal definition of classes in the programming language per say, it has functions, variables and objects (yes, objects, even if it does not have classes). Basically your JavaScript acts as part of your controller and should call PHP functions to carry out requests on the server. Remember OOP usually takes the MVC (Model View Controller) methodology.

So this code should fire when a message is received from an action. Pass the information to the PHP on the server and the PHP should save the information (as a JSON file or in a SQL database for example).

243

Answer

Solution:

It's important to note that "object-oriented programming" doesn't necessarily mean "class-based programming", so looking online for "how to write a class in JavaScript" will lead you up a blind alley. (JavaScript instead implements prototype-based programming which should be viewed as a different way to do OOP.)

In a lot of the simple cases you'll have in client-side scripts, you don't need to worry about inheritance, you just want to expose an object which has public methods and private state. So instead of diving right into prototypal inheritance (which takes a bit of getting used to), start by learning how to implement encapsulation, and privately scoped variables.

Here's a succinct introduction to basic public and private members, and below (and in this demo) is a quick abstract example of encapsulation (but no inheritance) using JavaScript's object model:

var my_object = function(start_value) {
    /* private variables */
    var some_number;

    /* private methods */
    function garble() {
        some_number = 42;
    }

    /* public methods and properties */
    var inst = {
        'set_number': function(new_value) {
            if ( new_value < 0 ) {
                garble();
            }
            else {
                some_number = new_value;
            }
        },

        'get_number': function() {
            return some_number;
        },

        'increment_number': function() {
            some_number++;
        }
    }

    // Initialisation
    inst.set_number(start_value);

    return inst;
}

var foo = new my_object(1);
foo.increment_number();

var bar = new my_object(-20);
bar.increment_number();

document.getElementById('foo').innerHTML = foo.get_number();
document.getElementById('bar').innerHTML = bar.get_number();

Note: I'm not an expert on JS OOP, and there may be gotchas or bad practices in my example above; if anyone more experienced spots one, please let me know in a comment.

People are also looking for solutions to the problem: xampp - How to install atom-autocomplete-php on atom editor?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.