Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP approach in PHP

Tags:

oop

php

I'm programming in PHP procedurally (is this even a word?) for about five years now and decided to try an OOP approach but ran into some concept/design problems. Let's say you have some modules in the program, every module has the possibility to list, add, edit and delete an entity. An entity can be..dunno, user, client, product etc.

How would you design the classes to manipulate these entityes?

Two possibilities came in my mind:

  • create classes for every entity with methods like getUsersList, addUser, editUser, delUser
    This approach seems resource consumingbecause in the script for the listing you only need the getUsersList and maybe delUser methods, while in the add user popup script, you only need the addUser method and in the edit user popup script only the editUser method. So, you have to instanciate an object and only use two or one of it's methods...
  • create general classes: listing, add, edit and delete and extend them for every entity this way you only have to instanciate one class at a time (the one you really need)

Thanks in advance,

like image 762
Catalin Avatar asked Dec 05 '25 08:12

Catalin


1 Answers

I would create an interface defining your list, add, edit, and delete methods. This gives you a class "template". If your classes (User, Client, Product, etc.) implement this interface, then the methods in the interface must be defined in those classes.

This will give you a similar "API" to access all the functionality of every class that implements your interface. Since each of your listed objects contains different data, the details of the methods will be different, and thus separate, but the interface will be the same.

Aside:

Your inclusion of "list" in your list of methods concerns me a little. It seems to imply that you are seeing your objects as collections of Users, Clients, Products, etc, where there should most likely be a User class that represents a single user, a Client class that represents a single client, etc.

On the other hand, "list" may be handled as a static method - a method that can be called without an instance of the class.

$bob = new User('bob');
$bob->add(); // Adds bob to the database
$fred = new User('fred');
$fred->add(); // Adds fred to the database

$users = User::list(); // Gives an array of all the users in the database

That's how I would handle things, anyway.

like image 163
Ryan Kinal Avatar answered Dec 07 '25 21:12

Ryan Kinal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!