简体   繁体   中英

Should I add classes to a RESTful API and why?

I've created a simple website using Angular for the front-end and Slim for the back-end API. I am wondering how classes could improve/hinder the API.

Example class

class Job {
    public $title;
    public $company;
    public $location;

    public function __construct($title = '', $company = '', $location = '') {
        $this->title = $title;
        $this->company= $company;
        $this->location = $location;
    }
}

The code below works properly, but I was wondering if I should add classes to the API and why? In other words, how would this class come into play?

Angular - Routing + Controller

function config($routeProvider) {
    $routeProvider.when('/add-job', {
        templateUrl: 'templates/add-job.view.html',
        controller: AddController,
        controllerAs: 'addCtrl'
    });
};

function AddController($http) {
    var that = this;

    that.add_new = function (job) {
        $http.post('api/add_job', that.job).success(function () {
        });
    };
}

Slim - PHP Service

require 'vendor/autoload.php';

$app = new \Slim\App; 

$app->post('/add_job', 'addJob');

$app->run();

function addJob($request) {
    $job = json_decode($request->getBody());
    $sql = "INSERT INTO jobs (title, company, location) VALUES (:title, :company, :location)";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);  
        $stmt->bindParam("title", $job->title);
        $stmt->bindParam("company", $job->company);
        $stmt->bindParam("location", $job->location);
        $stmt->execute();
        $job->id = $db->lastInsertId();
        $db = null;
    } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

OOP will help you standardize your data.

In the example you provided, the benefits may not be obvious. But, in the future, you may need to do some checks on the parameters. Those will be best placed in the constructor of the Job object. Then, you would have consistent rules, no matter in which part of your code you instantiate the object.

You may need, for example, to retrieve all the jobs attached to a company. Working with an array of Job objects will be much easier than working with table rows or a two-dimensional array.

I would also recommend defining your properties as private and use setters and getters to access them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM