r/PHPhelp • u/thegamer720x • Apr 08 '25
Right way to PHP OOP Implementation
Hi, I'm working as a full stack php developer. My job mainly requires procedural style php code. So I'm quite well versed with it.
Now, I have been trying to learn php oop. But no matter how many videos or guides i see, its still confusing.
Main confusion comes from
- File organization
- should each class be a seperate php file
- should utility class ( sanitization, uppercase, lowercase etc) be all combined in one?
- how to use one class in another class
- How to create class
- what should constitute a class. Should user be a class defining creation / deletion / modification of users
- what exactly should a constructor of class do ( practically)
I'm still trying to defer mvc architecture for now. In order to understand how the design and flow for oop program should be done
Any and all help with this is helpful. I understand the basics, but having difficulty with irl implementation. Please recommend any guide that helps with implementation rather than basics.
Thanks
4
u/tom_swiss Apr 08 '25
Generally, each class is in its own file. To use class A in class B, you include or require or autoload A.php into B.php. Depending on the architecture, a method in B might create, use, and throw away an A object; or you might pass an A into B's constructor for B to maintain a reference to.
You can have a utility class, or you can put utility functions in a namespace instead of a class.
At the code level, a class is a means of encapsulting a set of functions (methods) and a set of data that they operate on. At the design level, a class is a type of thing the system operates on, which each instance being an "object" of that class.
"User" is an excellent candidate for a class; there'd be an object of type "User" for Alice, another object for Bob, and so on. The constructor initializes the object; what that means depends on what you want to do with the object. It might load a user record from the database, for example.
4
u/equilni Apr 09 '25 edited Apr 12 '25
Why not take an simple procedural project and start refactoring, then slowly get to use classes?
The idea here is that you already know procedural code. Now refactor. Break things down logically - ie isolate and group database calls.
If you get here:
You are ready for:
$thisis an internal call in the class calling it's internal properties or methods. You can read up on it here.privatehere is the visibility of a property or method. You can read up on it here.Declaring
PDOafterprivateis type declaration, which you can read up on herenamespacecan be read up on hereThis is a good link (up to this section)
https://symfony.com/doc/current/introduction/from_flat_php_to_symfony.html
Or Modernizing Legacy Applications In PHP - video - works as a better intro
And obviously;
https://www.php.net/manual/en/language.oop5.basic.php
The whole chapter is a good read and reference.
It's cleaner to do so and will help with autoloading, esp using PSRS-4
See above for the basics
Loaded question. What should constitute a function?
This is a simple class:
A bigger one could have many more properties (variables) & methods (functions). As simple as this is, it has many benefits over an array - biggest is type safety and validation.
Adding types here again, which isn't OOP specific. You can read more on this here:
https://www.php.net/manual/en/language.types.type-system.php
https://www.php.net/manual/en/language.types.declarations.php
Dependency Injection. See the database class above? When I call the objects, it will look like this:
Also, add the
Postclass above with thePostDatabaseand you can return objects to work with later on:Use it:
Later on, you could update
insertandupdatemethods to use thePostobject vs separate parameters - ieinsert(Post)vsinsert(id, name). The internal code uses the class as a contract.2
u/martinbean Apr 08 '25 edited Apr 08 '25
Usually, yes. It’s easier (and more predictable) to find a class called
Userif you put it (and only it) in a file called User.phpI’d personally be tempted to split methods related to string manipulation (casing etc) from methods related to data sanitation. That’s if you need such methods in the first place, given PHP has lots of utility functions for things like changing the case of a string.
You can pass instances of other classes as arguments to other classes’ constructors and methods:
(Where
$productwould be an instance of aProductclass.)Classes should represent a “thing” in your application. Every time you use a noun (user, product, order, etc) then they’re candidates for classes. And then those classes should have properties describing that thing, and methods to do things to that thing.
Construct the class. If a class needs something in order to be instantiated properly, then it should accept parameters in its constructor to do the work needed in order to create a “good” instance of that thing.
So, for example, if you had a class for interacting with a third party API, you’d probably want some sort of HTTP client (like Guzzle) for making the actual HTTP requests to that API, and then also maybe an API key to authorise requests if the API requires authorisation. The class would be useless without those, so you could accept those two things as constructor parameters:
So now you can only instantiate
FooClientwith a HTTP client and API key; it’s not possible to have an instance ofFooClient, but then get errors in your code when you try and call methods$foo->getSomeEndpointResult()because it’s missing a dependency (although the class would still need to handle cases such as the API being down, forbidden responses from the API if the provided API key has expired or was invalid, etc).Which is a good idea. Keep building as you are now, but start looking for things that might be better off represented as a class that just procedural code. I will imagine there are lots of instances where you’re including files for functionality, or copying code, and code that encapsulates some business process but it’s just a sequence of procedural code that could instead be encapsulated as the entity its representing, with methods to do those business processes. Do small and slow refactors; don’t try and re-write everything that could be an object, to an object, in one go, as you’ll just end up with lots of half-refactored code that’s more difficult to grok than before, and also introduce lots of bugs. Focus on one specific thing, refactor it, test it, and once you’re happy, move on to something else.
5
u/eurosat7 Apr 08 '25
1.c) "composer autoload", "constructor injection"
2.a.1) A user is often only an Entity, that is something like a "DTO". You might have a Controller that is modifying the user.
I would advice you to work this through: https://symfony.com/doc/current/create_framework/index.html
1
u/HongPong Apr 09 '25
well study the symfony container
1
u/BarneyLaurance Apr 09 '25
Be careful with sanitization as a concept. It's been discussed a lot on here so I'll just quote __adrian_enspireddit
from https://www.reddit.com/r/PHPhelp/comments/yrj8ig/comment/ivu1app/
1
u/Majestic-Window-318 Apr 10 '25
Oh my gawd! OP is unfamiliar with classes! Please don't throw Symfony or Laravel at them, they'll give up on OOP altogether forever. Baby steps, guys!
1
u/tech_tech1 Apr 11 '25
If you want to read very basic, then check this W3 School post: https://www.w3schools.com/php/php_oop_classes_objects.asp
Otherwise, pick any popular PHP packages (OOP) and see how they are doing it.
PHP Sentry package: https://github.com/getsentry/sentry-php
PHP Stripe package: https://github.com/stripe/stripe-php
0
u/scottrichardson Apr 09 '25
My main tip for OOP is really focus on just staying with procedural! Procedural all the way baby! Just my OOPinion. Functional and procedural just seems way more…. Simple and sensible?
0
u/clusterconpuntillo Apr 09 '25
Thanks but I'm not in that process I already done it and I have a shitty framework
. But I wrote it from scratch and was really great experience
-1
u/suncoast_customs Apr 09 '25
I had this same existential problem on a large project. Resources were confusing, contradictory even. Here is what helped me, a published standard. All your questions are answered here.
https://www.php-fig.org