PHP Procedural vs Object Oriented

So my version would be something like this (I’m just modifying pbyrne84’s post) here:



define('REPORTING_DATABASE', 'reporting_database');
define('MAIN_APP_DATABASE_1', 'main_app_db_1');

/**
* @return Db
*/
function getDb($dbName){
    static $db;
    if( isset($db) ){
        //logic to parse the config file goes here
        return $db;
    }
    $db = new Db();
    return $db;
}  

//calling the function:
$db = getDb(MAIN_APP_DATABASE_1);

Then I’d have a config file with something like this:


reporting_database:
   host: xxx.xxx.xxx.xxx
   dbname: reporting
   dbusername: geoff
   dbpassword: hello
   dbport: 561


main_app_db_1:
   host: xxx.xxx.xxx.xxx
   dbname: main_1
   dbusername: geoff
   dbpassword: kjeifjeoj
   dbport: 561

The constants would map to the keys in the config file. Using the static variable would mean you would only have to do the parse of the file once on each request.

But see you can avoid stuff like:


    if( isset($db) ){
        return $db;
    }

in your DB function (which btw wont work unless you use a global $db (ugly and dangerous), you go to OO method: Heres how I like to do it.


class DbConfig {
    protected $Host;
    protected $Port;
    protected $User;
    protected $Pass;
    
    public function __construct($ConfigFile) {
        //parse ini file and pass to protected vars
    }
    
    /*
     * ALL GETTER functions
     */
    
    public function GetHost() {
        return $this->Host;
    }
    
    /*
     * etc...
     */
}

class Db {
    protected $Db;
    
    public function __construct(DbConfig $DbConfig) {
        //connect to db, set resource to Db
    }
    
    public function __destruct() {
        $this->$Db->close();
    }
    
    public function GetDb() {
        return $this->Db;
    }
}

$DbResource = new Db(new DbConfig('/path/to/this/scripts/db/settings.ini'));

He’s using a static variable here:


if( isset($db) ){
        return $db;
    }

So it will work, and it doesn’t need globals.

Your code would have to create the database connection each time, wouldn’t it? If I called it twice, I’d be creating a new db connection each time, whereas if you take my modified version of his code, you would only be returning the db handle (without using a global variable) unless you were making a connection to a different db (which actually would mean the code in my case should be modified to store an array of handles and return if created already, if not - create the connection)…

I just didn’t realise you could use static variables in a function outside of a class - but these are not the same as globals.

Everytime you initiate a new object, it will create a new connection, which is the proper behavior. You can reuse the same object that was already initiated to use the same connection.

But the challenge is to pass around the database connection in a procedural style without using globals. This function would do it - if you call it after the db is created, you’ll just receive the handle. If the handle isn’t created already, the connection will be made and the handle will be returned.

I’m not sure I agree a new connection should be created each time anyway. It’d be more resource heavy, unless you’re planning to just pass the database handle around all over the place?

  1. I’m not participating in your challenge.
  2. My way does not require a new DB connection, it requires one. You reuse the object that was created.
  1. It wasn’t MY challenge - it was the question we were all actually answering.
  2. If I call your function two times, I create two database connections, which is more resource heavy than just returning the database handle on the second function call.
  3. Passing the database handle around may not be such a bad idea - I was just pointing out that your method would be more resource heavy if it were not used this way. Personally, I use Doctrine for almost everything these days, so haven’t had to think about old school database handles in some time…

Your not using it correctly then. Call the resource, use the same resource over your script (if you want to) or in some cases as I quite often do, I decide to open a second connection for performance reasons. You can do 1 connection to run all your operations or 10. Its up to whoever is calling it.

Sorry to somewhat hijack the thread, but of those of you who use procedural, do you separate your code and organize it well? I separate PHP from HTML with procedural, functions are included, and overall it’s pretty organized.


$link = mysqli_connect('localhost', 'user', 'pass');
mysqli_select_db($link, 'database');
function WTF($link) { 
	$Q = mysqli_query($link, "SELECT * FROM Users LIMIT 1");
	while($R = mysqli_fetch_assoc($Q)) {
		print_r($R);	
	}

}
WTF($link);

Considering how much databases are used with anything, I certainly don’t mind providing the link. Is it really a big deal? I agree that procedural is noob if that’s all that is ever used, but also that it is great for a quick script with small complexity. I’m not a pro, so not like my opinion really matters!

Hi,

I have read many articles on OOP in hope to learn OOP and most of them say that functions inside a class is OOP.
I am not able to encounter any good article on OOP which really teaches on how to do OOP programming properly.

Can you experts suggest any ?

For now my aim is to learn:

  1. how to connect to db using oop
  2. how to run sql queries. You know i have seen code like $db-> (dunno how to do that)
  3. how to fix/sanitize user data.
  4. How to fetch a single and multiple records.

Whenever I try i fail to understand it and i go back to procedural method.

Thanks.

I frequently hear smart people recommend the book “PHP Objects, Patterns, and Practice” by Matt Zandstra. I’ve only skimmed it myself, but it looks to be a very good book. It teaches not only the basics such as syntax, but it also teaches how to think and design in an OO style. The latter is just as important as knowing the syntax, otherwise you may never get past thinking of a class as just a bag of functions.

Hi,

Thanks, i will check it out.

Thanks.

It’s a great book.

It’s quite dense though, and you probably won’t “get” everything right away. It takes time.

I’d say I really “got” objects for the first time when I first understood why one might use polymorphism in practise. Once I understood that (and it took me a while - for a long time, my objects were just basically procedural code wrapped in classes), the world of objects started making a lot more sense to me.

Once you understand why the phrase “code to an interface, not an implementation” makes so much sense, you’ll be on your way to getting it. I’m in work now so can’t type up a proper example, but perhaps later I’ll have a go at showing you a few examples… See what other people in here can come up with too :slight_smile:

You missed one of the biggest benefits (IMO) - the ability to unit test applications easily, which is hugely important.

I’m wondering whether it might be worth setting up a vagrant virtual machine with some unit tests and some basic objects to show people on here how objects can be so useful…

Problem is I’m always so busy with work, but if there’s interest in it, I may have a go at some point (perhaps some other people on here could help out?)… it could be a really cool exercise… I’m thinking we create a virtual machine with phpunit and unit tests setup, as well as some examples of how objects can be used in practice and host it on github somewhere, then provide a tutorial of sorts on here…

If people are interested in the idea, let me know… perhaps we can work something out together?

I wouldn’t say that is true really. Perhaps amongst amateur projects / hobby projects, and big names that have to deal with legacy, but don’t think it’s true for big projects, a lot of enterprise, or most of the open source community at all.

I have the book “PHP 5 Advanced” by Larry Ullman. His books are great he is very good at CLEARLY describing and showing examples of how to do things. This book covers OOP PHP in a few chapters and explains that OOP isn’t just a syntax change but a change of coding theory.

P.S. if there is ever a newb trying to learn PHP, I recommend “PHP 6 and MySQL 5” by Larry Ullman. Book covers everything from echo to creating an ecommerce system.

Indeed. The fact that Procedural style is more commonly used in PHP projects is a mere indication that there are a lot more beginner/amateur coders using this language. Apparently PHP is easy for newbies to start with, so it makes perfect sense to me. After all, true professional/advanced coders all use OOP over Procedural any time.