r/PHPhelp • • Mar 20 '23

Solved Object oriented programming - how do I create an update method?

So I have made lots of procedural php database commands before but on a new project I am attempting to use object oriented programming and following the MVC model.

Previously if I had wanted to update someone’s name in a users table I would have just said something like

‘UPDATE users SET name = ? WHERE id = 1’

However following the MVC model I am writing one method that will be used to update the user to avoid writing it more than once throughout the program.

If I do that, does it mean I have to pass a value for every column in my table every time anything is updated? How would I tell the method for example that I only want to update their name without writing a whole different method?

13 Upvotes

27 comments sorted by

5

u/kAlvaro Mar 20 '23

I'm not saying that MVC is bad per se, but when you first encounter it while learning it tends to have the side effect of making you think that all your classes must fit into one of those three letters.

To answer your question, your controller could look like this:

$user = UserModel::findById($id);
if ($user === null) {
    throw new NotFoundHttpException();
}
$user->setName($name);
$user->save();

Just be aware that this will serve you well until it doesn't, and it's fine. Real life projects have many more different classes because with nothing more than controllers, models and views, you end up with several thousand line files that are impossible to maintain. The important part is to understand the benefits of each solution, so you can know if you are doing it correctly and you can know when it's time to use something else. MVC is about separating three key components: input/output, business logic and display. If you can make changes to individual components without having to redo the entire application, you're on the right track. But your application can also additional components, esp. as it grows. For example, some frameworks have "services" (where you implement logic) and "repositories" (when you handle database interactions).

Don't worry too much. One step at a time.

1

u/Important_Material92 Mar 20 '23

Thank you that makes so much sense, it’s good to know it doesn’t have to be so rigid

1

u/32gbsd Mar 20 '23

MVC is bad

lol, shhhh but it is

2

u/Important_Material92 Mar 20 '23

I’m new to looking at it this way and on the surface is does look like a good idea to create the separation but the more I’m googling the more I’m finding conflicting information.

What could potentially be a better option?

3

u/32gbsd Mar 20 '23

You have to learn it in order to really understand why its a useful tool. Its not a case of which one is better or worse but knowing the "why".

1

u/ZippyTheWonderSnail Mar 21 '23

MVC is designed to solve a particular problem. All the design patterns built around Object-oriented programming are designed to prevent bad design.

There is both good and bad procedural programming. In fact, PHP is much maligned for decades of bad procedural code. However, there is also bad Object Oriented code; Usually when someone ignorant of design patterns creates a Wordpress style monstrosity. And for all the good things about functional programming, it is just as easy to create unreadable, spaghetti code.

The key is choosing the right tool for the right task, and implementing it in a way that produces clean code.

The question here is about using an ORM for CRUD. This is a complicated topic. Have a look at this tutorial on how an MVC works.

https://www.giuseppemaccario.com/how-to-build-a-simple-php-mvc-framework/

1

u/MrCosgrove2 Mar 21 '23

splitting the logic out from the controller has a lot of benefits, it lets the controller be just a go between, between the logic and the view. which, at least for me, allowed me the room to build more SOLID based code structures, and better unit testable code. overall , better code.

3

u/lovesrayray2018 Mar 20 '23

Think of how an instance can accept multiple parameters of different types. You need to first define the structure of the class/method you use for updating any and all data.

For example your update function could receive the data as an associative array as one parameter, and the column name that will be used to select whcih column to update as the second.

Now you create a custom query string that dynamically generates the list of columns to be updated by splitting the array keys and values using array_keys and array_values, also inserting the where value based on second param and then run this dynamically generated query

1

u/Important_Material92 Mar 20 '23

This is essentially what I started doing but I was struggling splitting the arrays and successfully making a prepared statement work.

5

u/SomeOtherGuySits Mar 20 '23

Implement an orm

3

u/Important_Material92 Mar 20 '23

I feel some Googling coming on

6

u/SomeOtherGuySits Mar 20 '23

It’s a worthwhile goog. Take a look at symfony and laravel and how they use doctrine and eloquent.

If you are doing the project to learn about MVC then roll your own just for discovery, but if it’s for commercial use I’d recommend using either symfony or laravel for the project.

1

u/Important_Material92 Mar 20 '23

Thanks I’ll have a look 👀

1

u/BinBashBuddy Mar 22 '23

If the db is what you're concerned with use illuminate, it's the ORM that Laravel uses. I'm working with very old procedural code and originally replaced most of the mysqli calls with PDO, but a couple years ago I started replace those with using illuminate/database. I use laravel in the new sites I build for my employer, but having illuminate has really cleaned up the code in this older stuff I have to work with.

0

u/czbz Mar 27 '23

Or pick an ORM off the shelf. I'd recommend Doctrine ORM.

But you certainly don't have to have an ORM - writing SQL by hand is often a very reasonable option.

1

u/bigByt3 Mar 21 '23

Maybe I'm misunderstanding your question but I feel like all of these other answers are over complicating what you're asking.

I also think learning OOP principles and writing your own functions/classes is key to development as an engineer, it helps to understand the underlying fundamentals when you pick up an ORM or Framework.

With that said you can do what you're asking in any number of ways but the easiest would be to create a set of query builder functions that use dynamic variables and PDO. From there you can expand on it if you want to create your own reusable framework. It can be tedious but the reward is worth it.

2

u/Important_Material92 Mar 21 '23

I started by trying this actually but I keep hitting a brick wall. I have a class method which is building my query by splitting out the array keys and the array values and then creating a sql statement. This works perfectly when the array only has one item but as soon as I add more than one I get the error

“MySQL::bind_param() number of elements in type definition string doesn’t match number of bind variables’

But it does. With two items in the array my bind looks like this and still gives me this error

$types = “ssi”; $values = “bob, cratchett”; $id = 1;

$stmt->bind_param($types, $values, $id);

1

u/bigByt3 Mar 21 '23

Rewrite $values as $values = ["bob","cratchett"];

2

u/Important_Material92 Mar 21 '23

I tried that but still getting the same error. It seems like the commas in the variable/array aren’t being read properly by the bind_param. I think it’s counting it still as one parameter

2

u/bigByt3 Mar 21 '23

I'm not 100% sure because I don't use bind_param but it looks like an array needs to be preceded by a ...

I would refer to the docs on that to be sure

2

u/Important_Material92 Mar 21 '23

You’re right, thank you. I got around it by (in case anyone else sees this thread);

$data = array_values($data); $stmt->bind_param($types,…$data);

1

u/bigByt3 Mar 21 '23

Glad to help!

2

u/[deleted] Mar 20 '23

You don't necessarily need an ORM, any strategy to provide a database abstraction layer will do. The ORM (particularly the active record variety) just happens to be the most common/popular abstraction. With that said, the ORM pattern does lend itself to CRUD based operations nicely so it may be a the best answer for your use case.

1

u/Atulin Mar 20 '23

Just use Doctrine ORM

1

u/32gbsd Mar 20 '23

You are in for a world of pain and a hundreds of hard coded references. First thing they will tell you is use an ORM, then use framework X, SASS and a bunch of auto wiring tools. There is a website called TODOMVC which has some examples that you can look at. There should be one for PHP.

1

u/itemluminouswadison Mar 21 '23

Check out laravel eloquent for an easy orm

1

u/alexbarylski Mar 21 '23

If you want a truly object solution and ORM is the way to go. They come with some overhead and sophistication but they also abstract relational ideas into a purely object realm.

Use Doctrine, it’s an excellent platform. It is truly life changing.

Alternatively you could implement a simple table data gateway or active record/data mapper.

They don’t typically implement a full object approach. Usually every table has a 1:1 relationship with php classes. It’s a half baked solution in moving towards an OO paradigm, but it’s a wee bit better than procedures.