views:

79

answers:

4

Hi there,

I'm going to write a booking website using php and ajax and I really can't figure how to mix these two tools with a strict object oriented design.

I was used to make a call using ajax to a php web page that returns the right set of values (string, xml, json) in a procedural way.

With object oriented programming how is it supposed to work?

The simplest solution that i can think is to call through ajax a php page that should only instantiate a new object of the right class and then make an echo on the result of a simple call with the data received but this doesn't look very oo...

For example to implement the register function I should make an ajax call to a register.php web page that, in turn, will instantiate a new Registration object r and then simply calls r.register() with the right data.

Is there a better solution to this problem?

I want specify that I can't use any php framework because it's a didactic project and I have this rule that I should respect.

Another specification: I've read a lot of tutorials that describe how to write your own mvc framework but doing this seems to be an overkill for my problem.

Thank you for your help, every idea will be appreciated.

A: 

A website should really work without JS/AJAX. Get this bit right first and then add the bells and whistles using JS/AJAX.

matpol
TheSENDER didn't say he wasn't doing that, and this doesn't answer the question.
David Dorward
ajax is javascript isn't it - I would never recommend that a site using php relies on ajax to work. I find it annoying that people don't separate these things out - programmers seem to want to use all their toys without thinking about accessibility and usability.
matpol
Still your answer doesn't have anything to do with the question. The question was about how to use OOP techniques with Ajax in a didactic project not if JavaScript should be used or not. And there are many valid reasons for a modern web application (not just a web site) to rely on JavaScript and AJAX to work.
Daff
I didn't say not to use it I said get the website working and then add it. Surely this is best practice? I think it does relate to the question in terms of workflow.
matpol
A: 

As you already said you don't really need a PHP framework and don't need to build your own MVC implementation (especially if you are e.g. working with JSON or XML). Basically you are pretty free on how to do your OO model, so your idea is not necessarily wrong.

Some OO anti patterns I have seen people using in PHP:

  • Use global variables in classes
  • Create classes without member variables resulting in method calls being the same as in a produral style
  • Directly accessing $_GET, $_POST etc. in a class
  • Echoing html output (imho this should be done in view templates)

An example for what you might want to do for the registering process processing some $_POST variables and returning a JSON success message:

<?php

class Registration
{
    private $_data;

    public function __construct($registrationdata)
    {
        $this->_data = $registrationdata;
    }

    public function validate()
    {
        // ...
    }

    public function register()
    {
        // ...
        if($this->validate())
            return array("registered" => true, "username" => $this->_data["username"], 
                "message" => "Thank you for registering");
        else
            return array("registered" => false, "username" => $this->_data["username"],
                "message" => "Duplicate username");
    }
}

$reg = new Registration($_POST);
echo json_encode($reg->register());

?>
Daff
That's exactly what i was thinking. Maybe session management could be a bit problematic in this way because it becomes a cross cutting concern.
TheSENDER
I think you won't be able to entirely get rid of having to deal with cross cutting concerns. As for security and session management the MVC pattern works quite well because you can always do it in your controller before anything is done.
Daff
But I think that the model of code you've posted needs to be changed a bit. Before the input validation (obviously not in the registration part) I think I should check the session validity and so almost every controller object constructor will need to take a session argument. Am I right?
TheSENDER
The controllers yes, but design wise I would let the Registration class assume that there has been dealt with session and security management already.
Daff
+1  A: 

There is no reason to create any classes if all you are doing is calling a couple of unrelated stateless php functions.

Martin Wickman
I have to manage sessions and databases, i presume it will be simpler if I use a full oo approach.
TheSENDER
A: 

Object-Orientation transcends PHP and AJAX. To write an OO solution, you should first understand and describe the objects in the problem domain, along with their responsibilities.

A booking website, for example, might have classes such as:

  • Appointment
  • Calendar
  • Client
  • Vendor

Describe the responsibilities of these classes. For example, client objects might have the ability to schedule an Appointment with a particular Vendor. This might look like:

client.schedule( appointment, vendor )

The responsibilities and collaborators that you describe should be applicable to any OO language. Once you have defined the basic classes (user stories can help here), start thinking about how to move the data from the user interface into the domain classes, and vice-versa.

One idea, that skips the MVC controller, is to give the responsibility of reading and writing data to the class that holds the data. Consider:

class Client {
  function toJSON() {
    // Create a JSON string.
  }

  function fromJSON( json ) {
    // Set the local variables here.
  }
}

Note that how the data is transformed into XHTML remains independent of the model at this point. That is, toJSON() could just as easily be toXML() or toString().

I would then make session-based authenticated services for queries. For example, to retrieve a list of cities, make a file called city.php:

<?php
include_once( 'db.php' );

try {
  $link = db_connect();
  $name = strtolower( db_safe( $_GET[ 'q' ] ) );
  $name = empty( $name ) ? '' : $name;

  db_json( "SELECT c.name WHERE c.lowercase_name LIKE '%$name%' LIMIT 10" );

  db_close( $link );
}
catch( Exception $ex ) {
  db_close( $link );
}
?>

Here, the database functions (such as db_connect(...)) could be encapsulated in a class, then that class is used to query the database. Notice that using a class like this would help decouple the code from a particular database.

These services would allow you to query various pieces of information. The user interface, being XHTML and JavaScript, could then use jQuery or other such framework to handle client-side events. For example, to present a Facebook-like tokenized input field UI for selecting a city:

  $('#city').tokenInput( HOST + 'city.php', {
    hintText: "Type a city name.",
    tokenLimit: 1,
    classes: {
      tokenList: "token-input-list-facebook",
      token: "token-input-token-facebook",
      tokenDelete: "token-input-delete-token-facebook",
      selectedToken: "token-input-selected-token-facebook",
      highlightedToken: "token-input-highlighted-token-facebook",
      dropdown: "token-input-dropdown-facebook",
      dropdownItem: "token-input-dropdown-item-facebook",
      dropdownItem2: "token-input-dropdown-item2-facebook",
      selectedDropdownItem: "token-input-selected-dropdown-item-facebook",
      inputToken: "token-input-input-token-facebook"
    }
  });

Lastly, implement handlers for the various inputs. These handlers would be responsible for parsing the form data (from HTTP request parameters to the format expected by the class instances [i.e., JSON]), instantiating the requisite objects, and then asking the objects to perform the appropriate task.

Dave Jarvis