Jump to content

Building API, PDO, Procedural


Adamhumbug

Recommended Posts

Hi All,

I am looking to explore the world of API's and i would like to build one.

I have had a look around online and most of the examples use classes and are OOP.

I have never done OOP before and although i am sure it is something i should be looking into, i wondered if either anyone could point me in the right direction or suggest any good reading around this topic.

I am starting by just trying to send a list of Clients in the response.

Thanks in advance as always.

Link to comment
Share on other sites

An API is a contract that says "if you give me X then I will give you Y". It has nothing to do with OOP. So it's totally valid to build an API with code that's procedural.
In fact, a lot of OOP is just syntactic sugar over a procedural pattern. Take PHP's cURL functions for instance: you create an "instance" of a cURL thing, then call different "methods" using that thing - whether you write "curl_function($instance)" or "$instance->function()" doesn't make much of a difference.

So what's your goal here? To build an API and you think you need OOP for it? Or to learn OOP using the idea of an API as a real-world example?

Link to comment
Share on other sites

Thanks for that explanation - appreciated.

My goal here is to build another site, that is seperate from my first one that can call an API in the first to get certain information.

Eventually it will be a site that can be logged into and using the apis it will grab the information that it needs from the first site.

I am sure that there are other ways of doing this but i wanted to use it as a way of learning apis as well as building something for a reason rather than it being hypothetical.

As mentioned i have seen some tutorials that are OOP but i find them hard to follow or they are so specific to that project that i struggle to break out what i need.  I am looking to start basic - grab all client names from client table - return json.

Also i know that i will need it to be secure, so i want some sort of key exchange in there which i also have no idea about.

Edited by Adamhumbug
Link to comment
Share on other sites

Object-oriented programming tends to be one of those things that doesn't really make sense until you find the right piece of information, or read something phrased in just the right way, or happen to be in the right frame of mind, at which point it all starts to click together. Which makes it hard to explain or teach.

But basically, think of what you're doing - whatever it is - in terms of "Things" and the "Actions" those things can do. For now, forget programming and try applying it to real-world concepts.

For example, I'm here sitting at my computer. The computer is a Thing. It has a power button, which also counts as its own Thing if you really want to go that deeply into it. If I perform the Action of "press the power button" on my computer, it'll either turn on (if it's off) or start shutting down nicely (if it's on). Or I can press the power button for a few seconds, in which case it'll either turn on or it will immediately turn off. And if I were to sketch that out in some pseudo-code, it might look like

thing Computer {

    action PressThePowerButton(HowLong) {
        if PoweredOn {
            TurnOn // doesn't matter HowLong I pressed the button for... I think
        } else {
            if HowLong == Short {
                TurnOffGracefully
            } else {
                TurnOffImmediately
            }
        }
    }
    
}

For another example, I'm hungry because I haven't eaten today, so I'm going to go into the kitchen and cook something. I'll be using my stove Thing. It has four burner Things, each wired to one of four corresponding knob Things, and I can turn the knob right/left to turn on/off the associated burner.

thing Stove {

    has Burner1
    has Burner2
    has Burner3
    has Burner4
    has Knob1
    has Knob2
    has Knob3
    has Knob4

    action Manufacture {
        Knob1 = create a new Knob connected to Burner1
        Knob2 = create a new Knob connected to Burner2
        Knob3 = create a new Knob connected to Burner3
        Knob4 = create a new Knob connected to Burner4
    }

}

thing Knob {

    knows about a Burner
    
    action TurnKnobRight() {
        set Burner on
    }
    
    action TurnKnobLeft() {
        set Burner off
    }
    
}

thing Burner {

    has Temperature
    
    action SetOn() {
        Temperature = High
    }
    
    action SetOff() {
        Temperature = Off
    }
    
}

Basically, 95% of OOP is thinking about Things and Actions, and by doing so you can take a complicated concept and reduce it into smaller pieces that are easier to manage. Like how I didn't try to "code" all the burner and knob stuff in one place: the knob knows how to do knob things, the burner knows how to do burner things, and they're hooked up to each other.

But now I'm really hungry.

  • Like 1
Link to comment
Share on other sites

Studying design patterns such as MVC (Model-View-Controller) and Active Record Design has enhanced my understanding of Object-Oriented Programming (OOP). Although many prefer Model-View-Controller, I found Active Record Design more helpful in solidifying my grasp of OOP. One constant with OOP is that there's always something new to learn, and there's always someone with a deeper understanding of it.

I believe that beginners often find the structure of Object-Oriented Programming (OOP) challenging. Here's an example from some code on my website to illustrate this. ->

    // Display Record(s) by Pagination
    public function page($perPage, $offset, $page = "index", $category = "general"): array
    {
        $sql = 'SELECT * FROM '. $this->table . ' WHERE page =:page AND category =:category ORDER BY id ASC, date_added DESC LIMIT :perPage OFFSET :blogOffset';
        $stmt = $this->pdo->prepare($sql); // Prepare the query:
        $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data:
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

Initially, I would mix up my code by writing `$sql` and `$this->sql`, which made things confusing for me. However, everyone has their unique journey in learning Object-Oriented Programming (OOP). By coding in this manner, I'm able to more clearly identify key OOP components, such as recognizing `$this->pdo` and understanding that `$stmt->fetchAll(PDO::FETCH_ASSOC)` is an example of object-oriented code.

Link to comment
Share on other sites

  • 3 weeks later...
On 12/22/2023 at 5:45 AM, Adamhumbug said:

Thanks both thats really helpful.

 

Would you suggest then, that when looking at making the API that i try and do this with OOP rather than POP.  It seems far more popular to use OOP for this.

I'd say you should at least give it a shot. I'd probably do it the OOP way if I needed an API, too.

Of course, it probably depends on complexity. If I needed an API to only do one or two things, I'll just use POP (because it's dead simple) and then clean up my code. On the other hand, if I needed an API to do a lot of things, I'd probably take the time to plan it out in an OOP fashion and get started based on that.

Link to comment
Share on other sites

HTTP based API's typically have a design.  One popular way of creating an API is to utilize REST.  I would encourage you to search for "REST API" and read some articles on it.  It is not a cut and dry thing, but there are some important concepts to understand, and the best practice for applying HTTP methods GET/POST/PUT/DELETE as well as understanding the idea of idempotency in relation to resource location.  

Generally speaking, most api's are REST api's.  

It's also been a common best practice in most cases to utilize json as the format of data transfer (which is not dictated by REST or RESTfulness).

Where OOP comes in, is that you want to think about and abstract the "entities" your application works with.  As OOP is great for organizing data, I would highly recommend its use, and to think about the entities present in whatever application you are trying to create.  There is a lot of overlap in these areas, with relational database design.

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.