Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO PHP + Ajax without framework

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.

like image 656
TheSENDER Avatar asked Nov 06 '22 11:11

TheSENDER


1 Answers

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());

?>
like image 126
Daff Avatar answered Nov 11 '22 05:11

Daff