Jump to content

what is the best approach ? Use Classes, use functions or something else ?


MrMagic909

Recommended Posts

Hi everyone,

I have a couple questions about approaches to coding

First off, I am used to creating functions for certain tasks and putting them in a functions.php, now i've done stuff with classes in the past too ...  but now with all the changes in PHP8 .....

What is the best way to go when using the PDO style ?

Also I noticed I had created a db_connect.php that I include, but I also created a function to connect and close a database ... is this wise, and if not what is the best way to go about this ?

thanks i.a. for any assistance ;)

Link to comment
Share on other sites

Everybody has their own preference.  Personally I write without using a framework and I don't use classes either.  Write my php using functions and included php modules to handle security checking, db connections along with a bit of JS and a well-organized std. HTML template that I populate with php variables to create my page.

Have at it.

Tips that I find handy:

- don't use upper and lower case in your php

- make good use of heredocs

- use POST or GET but never REQUEST

- use PDO for your db connection and querying.  Repeat - use PDO.

- and of course design your database properly.

Link to comment
Share on other sites

I use classes as I like mobility of the code going from one website to the another is easier for me. I don't use Frameworks or Libraries. I like using Vanilla JavaScript as I don't have to think about having a library. I find out that I really don't write that much more code just using good old plain JavaScript.

 

Here's a JavaScript Online Trivia game that I updating. I am using CodePen to do a mockup first of it -> https://codepen.io/Strider64/pen/NWEpZdj

Like already stated everyone has their own coding style and I am sure you will find yours.

Edited by Strider64
Link to comment
Share on other sites

Hi @ginerjm, thanks for the reply, and YES I have started using PDO on advice from alumni & moderators here :) 

I started with a base mysqli but was advised to adopt pdo, so I am taking what I've already written into pdo territory.

can you elaborate on the following

-  included php modules to handle security checking

- a bit of JS and a well-organized std. HTML template that I populate with php variables to create my page.

- make good use of heredocs

?? 
I would like to understand more about how you organize these things, and I have no idea what heredocs are / is ? :) 

 

greets

 

Link to comment
Share on other sites

It really doesn't matter - I personally like OOP, even in plain PHP projects. However, when I start something new I reach for Laravel because my jobs have used Laravel for the past 4 or so years and by now I'm somewhat familiar with it. I also liked CodeIgniter 4, though there's not as much built-in functionality there as Laravel (but that can be nice as there's also not as much magic to deal with).

Biggest problem I find I have nowadays jumping into a procedural or functions-based system is keeping track of what function comes from where. When everything is in the global namespace I find that things can get messy and confusing.

Link to comment
Share on other sites

I  have written several modules (files containing small important pieces of code) that handle some standard features that get used all the time.  Like checking the log in credentials for my apps or for making a db connection as well as some other particular operations that I use sometimes.

As for heredocs Barand has pointed you to the Manual so that yyou can read up on that.

I have a php function that I use for many of my scripts that outputs my standard html page which I modify for each page to handle what I need to adjust for that particular page.  A big part of that is to add the div/form tags that I may need but the dynamic data that may be part of that is added after being built outside of this function.  Keeps the html clean and all I do is insert a variable to display the data that I have formatted for it.  The css is also part of this function.  Something like this:

....
...
if ($tbl_results)
{
	echo "<div id='tbl_box'>
	<table id='rslts_tbl'>$tbl_results</table>
	</div>";
}
      
        

where the variable is built before calling this display function with all of the html table's content already built.

Link to comment
Share on other sites

One of the benefits of the PHP ecosystem is that it has not one, but 2 of the best web application MVC frameworks in existence, those being Laravel and Symfony.  I've used both and either one is a great starting point for creating a web application.    I have created or worked on large applications in both frameworks, although I will admit that I'm biased towards Symfony.

Symfony is typically paired (and somewhat bundled) with the Doctrine ORM, but Doctrine can be used independently in a project.  What is more, Doctrine has several components, including a "Database Abstraction Layer"  aka DBAL, that provides a nice wrapper around PDO.

Not too long ago, I created a little proof of concept app, based on a forum question, and I put this web application on github, and I reference it now, because it was made using DBAL.  It's an example of a simple web app that only uses 3 components, with the primary one being the DBAL wrapper.

It also illustrates some best practices, in terms of where to put custom classes,  what sort of minimal directory structure your project(s) should have, an implementation with a quasi-front controller, and composer for downloading components and autoloading.  I also used the CSS framework Bulma.    I'd suggest git cloning it, and poking around in the code.  You could also experiment with adding some components, or unit tests.

With that said, once you consider what a larger projects would need, not to mention the lack of routing, or views, before long it becomes pretty apparent that you're just better off getting the MVC from Symfony or Laravel.  Template engines like Twig or Laravel's Blade have some great features like partials, helpers and template overrides (which are sort of like child classes for templating) that go a long way for separating concerns.  Certainly, you can create your own framework, as many others have done, but by the same token, most home grown frameworks, end up implementing some form of MVC anyways. 

Link to comment
Share on other sites

Allright @ginerjm, got it! That's basically how I approach coding, in a modular way ie I create a piece of code that performs a certain function that gets used a lot. I might start using laravel or symfony just so I can escape writing all those pesky little subroutines like login, registration, password hashing, difficulty checking etc... I mean I presume those kinds of things have already been done to death by others and should/would be available in a framework, right ?

I have a similar approach to displaying content, I use a function : echo (getContentByType("head1")); to display a header, pagecontent and footer, I will have to look into simplifying that to your approach where it displays the entire screen , introducing pre filled variables.

I tried reading the pages on heredocs, barand sent through but as of yet it doesn't make a whole lot of sense to me ... I will need to read it couple more times I guess and perhaps reference some other sources.

anyway thanks for the tips bruddha, much appreciated

Link to comment
Share on other sites

Hey @gizmola

like i said earlier to @ginerjm, I will probably end up use a framework later on, just for the ease of use in larger scale apps, however for now I am writing a relatively simple app with 1 function/goal to it. I want to write a script / create a website where I can submit websites (that I add to the database as a user) to different types of ad sites i.e. classified ad sites, link directories, search engines, specialty ad sites etc etc

But as I am used to mysql/myqsli for now I have to focus my attention on getting the whole PDO approach under my belt and then go from there. I have my own xampp running and setup a site with some basic code for homepage, login and registration and on my xampp it runs, however when I put it on a live server I get nothing but 500 error

sooo gonna go dive in to that first :P 

thanks for the help bruddha 

Link to comment
Share on other sites

You use the heredocs construct to output html or js code within a php script without having to switch modes all the time.  Here is a sample of what you can do:

$code = '<table border=1>';
$col1 = 'col1';
$col2 = 'col2';
for ($i=0;$i<2;$i++)
{
	$code .= <<<heredocs
	<tr>
	<td>$col1</td>
	<td>$col2</td>
	</tr>
heredocs;
}
  $code .= '</table>';
echo $code;

You can create your output using php and html without having to do the <?php  and /?> mode switching all the time.  I basically hardly EVER switch out of php mode by using heredocs.

Link to comment
Share on other sites

On 7/2/2023 at 8:24 AM, MrMagic909 said:

Hey @gizmola

But as I am used to mysql/myqsli for now I have to focus my attention on getting the whole PDO approach under my belt and then go from there. I have my own xampp running and setup a site with some basic code for homepage, login and registration and on my xampp it runs, however when I put it on a live server I get nothing but 500 error

 

 

This is why I linked you to the github project.  Did you take a look at it?  Clone and run it locally?  Try and understand what it does and how it is designed?  It's essentially a sort of PHP SPA.  If you look at all the functions I had to add for the simple routing and handling of the form, you get an idea of what a routing class, or the HTTP classes that lots of projects (Laravel included) borrow from the Symfony components.  

 

In summary, frameworks are a collection of different component classes, usually with things like configuration figured out.  My demo project includes use of a "dotenv" processing class, which is best practice for web app configuration of things like database credentials which should not be hard coded and stored in your source code repository.

You don't have to use use an entire framework, but instead can use components you find helpful.

Also, again, DBAL wraps PDO.  By using DBAL, you will be using PDO, only in a simplified form.  It has some very nice features, one I illustrated and documented.  When you use symfony or laravel, you won't be using PDO directly -- you use their ORM that then uses PDO for you.  My project would have been even smaller and simpler if I'd used the Symfony Http foundation component.

My point is, that modern PHP development should always start with the user of composer, and a skeleton directory setup with a /public directory where directly executable scripts will go.  All classes should go into either your own component, or in an app space.  You make at most a few modifications to the composer.json, and as you develop, rely on composer to generate the autoloader you need, which you include in any of the script that directly execute within /public.  An alternative to that is to create a bootstrap include that does the same thing, and include that in all your directly executable scripts.

Link to comment
Share on other sites

An object-oriented approach has a lot of benefits over a functional approach, particularly when paired with a good IDE.

Autoload support

If you structure your classes according to the PSR-4 standard, you can let an autoloader script manage including your classes when needed.  This means you no longer have to manual deal with making sure you have included the correct files on your pages, or just include everything to be safe.  You can just use your classes as needed and let your autoloader script automatically include the class file when necessary.

Autoloading of functions is currently not possible, though that might change eventually.

 

Data management

Something every program needs to do is manage and work on data.  With a functional approach, that often means you use a lot of associative arrays to hold your data and pass those array's between functions.  While this works, over time it becomes hard to manage as you will loose track of what keys exist in what arrays and different code paths may end up diverging in how they manage those arrays.

Even using just simple objects can help with this by providing predefined properties for your data structures.  When paired with a good IDE, you will be able to able to easily see what properties are available on an object, get auto-completion of property names as you code, and easily refactor the data structure if necessary (ie, rename a property).

 

Automated Testing

OOP lends itself well to automated testing thanks to features like interfaces and inheritance.  With functions, you end up with hard-coded references to other functions through out your code.  The implementations of those functions cannot be easily changed for testing.  By passing around objects and calling methods instead, you can easily replace your real object with a fake / mock object for testing purposes. To take full advantage of this, you need to not just use OOP, but also techniques like dependency injection so you don't just replace a hard-coded function with a hard-coded class reference.

 

Reuse

While both functions and classes allow one to re-use code, I generally find that making reusable code is easier done using an OOP approach.  Often in order to be reusable, code needs to be flexible. 

To manage that with functions you either end up making a lot of different functions, or your functions need to have a lot of parameters (or a single large array parameter) to control the functions behavior.  This leads to a messy code base and can make future edits hard to make without inadvertently affecting some use case.

With an OOP approach, you can control behavior though either properties that can be set individually as needed, or by breaking things down into various objects that can handle different use cases.  This lets the code be cleaner by removing various conditional branches and helps isolate future changes to specific areas without affecting other areas.

 

You need to know OOP anyway.

The vast majority of libraries out there are using OOP, so if you want to take advantage of other peoples work to save yourself time (ie, the various frameworks or even just individual libraries) you need at least a basic understanding of how OOP works.  You don't need deep knowlege of everything OOP and all the design philosophies t hat go with it just to use a few libraries, but you do need basic syntax and structure knowledge to understand the library code and know how to interface with it.  The more you know though, the easier it is to integrate with libraries and customize them to suit your needs.

 

  • Like 1
Link to comment
Share on other sites

On 7/2/2023 at 4:45 PM, kicken said:

 

You need to know OOP anyway.

The vast majority of libraries out there are using OOP, so if you want to take advantage of other peoples work to save yourself time (ie, the various frameworks or even just individual libraries) you need at least a basic understanding of how OOP works.  You don't need deep knowlege of everything OOP and all the design philosophies t hat go with it just to use a few libraries, but you do need basic syntax and structure knowledge to understand the library code and know how to interface with it.  The more you know though, the easier it is to integrate with libraries and customize them to suit your needs.

 

 

This is really the crux of the issue.  Applications are rarely written from scratch -- they are assembled from component libraries (a collection of OOP classes).   You don't have to know how to write your own OOP code immediately, or even to write any sophisticated OOP to make use of other peoples components.  This is why you really want to start with composer and learn enough about that to start making use of components that will make your application faster, and better quality in the vast majority of cases.  You can always verify the quality of the component, by looking at and even running unit tests they have written for the library.  You need to know the basics of oop, but you don't have to be an OOP expert.

Link to comment
Share on other sites

  • 2 weeks later...

Well, the best methodology for coordinating your code with PDO relies upon the particular prerequisites and intricacy of your task. Both approaches are valid, and you can choose the one that fits your needs and coding style better.  

Thanks  

Link to comment
Share on other sites

On 7/20/2023 at 4:47 AM, aarti789 said:

Well, the best methodology for coordinating your code with PDO relies upon the particular prerequisites and intricacy of your task. Both approaches are valid, and you can choose the one that fits your needs and coding style better.  

Thanks  

Did you get this from chatgpt?  This literally says absolutely nothing, as it refers to 2 "approaches" neither of which were listed.  It's like you cut and paste from something else.  I hope your future posts will be of more value than this one. :(

Link to comment
Share on other sites

On 7/22/2023 at 12:52 AM, gizmola said:

Did you get this from chatgpt?  This literally says absolutely nothing, as it refers to 2 "approaches" neither of which were listed.  It's like you cut and paste from something else.  I hope your future posts will be of more value than this one. :(

Well, I seached it on Google and ChatGPT both and conclude. Sorry for inconvince, I will take care about it for future reference.  

Thanks    

Link to comment
Share on other sites

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.