Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Tell me if I'm explaining this correctly...

I'm working through an app that I didn't build and I'm encountering some new syntax and I want to ensure I'm understanding it correctly.

I've got this:
class Application
{
    private $cn;

    function __construct(PDO $conn) {
         if(!isset($conn))
              throw new Exception('Wrapper objects must be passed a PDO Connection object ($this->cn) upon construction');
    $this->cn=$conn;
    }
}

Open in new window

What's going on here? I'm thinking you're setting up a variable called "cn," but I don't get where $conn is coming from and why, from a syntax standpoint, it's prefaced with "PDO."

What is this?
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bruce Gust

ASKER

Gentlemen!

As always thanks for taking the time to explain the "why" as well as the "how."

I've got a very surface knowledge of .NET and it was there that I first heard "Dependency Injection." I was also exposed to the practice of establishing the datatype before actually assigning a value to a variable, so most of this is familiar. I just hadn't seen it PHP before.

Let me explain it back to you, just to make sure I'm tracking with your correctly.

A Class, by itself, is a body of code that just exists. It's not being used unless it's "instantiated." Think of it like a greyed out button. In order to activate that button, you have to instantiate it.

When you do that, you now have an "instance" of that class. You may have more than one instance, so for the sake of keeping things straight, each unique instance is referred to as an "<a href="https://en.wikipedia.org/wiki/Object_(computer_science)" target="_blank">object</a>."

Now that you have an "object," you can systemically click on it and be able to access all of the functionality of the Class that's represented by that Object.

So, "PDO" is a Class that represents all of the syntax you need to talk to a database.

$conn= new PDO('database creds'); //this is an instantiation of the PDO class and you're calling this particular instantiation $conn. $conn is a PDO object.

With your PDO object, because you need a database connection each and every time you interact with the database, it would be very convenient to have that connection established within a Class so you don't have to fire it up every time with each and every Method you have within your Class. That's what's happening with this example:

<span class="blue">class Application
{
    private $pdoConn;

    function __construct( ) {

    $this->pdoConn = new PDO('sqlite:/home/domain/slite0/employees.sql3');
    }
}

$ myApp = new Application();// PDO is connected inside Class code</span>

With the app.class.php page, you're using Dependency Injection.

A "dependency" is a body of code that your object "depends on" in order to function. In this case, the PDO connection is the "dependency" that your Application Class requires.

In the example above, we took care of that by setting up the $pdoConn variable and then, with the construct, we established the PDO class as a parameter an then assigned it to the $pdoConn. In other words, using the construct, we instantiated the PDO class and assigned it to the $pdoConn variable making $pdoConn an object of the PDO Class. And all this was done within the Class.

With "Dependency Injection," you take a slightly different route - and that's what we've got here.

Instead of doing all the heavy lifting with the Class, we're going use the constructor to set up a variable that we've declared previously as having a specific "type." That's what this is:

<span class="blue">class Application
{
      private $cn; <span class="green">// "private" can't be shared outside this Class</span>

      function __construct(PDO $conn) { <span class="green">// establish the $conn parameter as a PDO datatype</span>
            
            if(!isset($conn))
            {
                  throw new Exception("something went south...:);
            }
            
            $this->cn=$conn; <span class="green">//assign the $conn parameter to the "cn" property</span>

      }      
}</span>

This code by itself is incomplete, however. We've made $cn a PDO object, but there aren't any credentials being referenced or a database. THAT is what's being injected when you instantiate the Class.

Like this...

<span class="blue">class Application{
      
      private $cn; <span class="green">// "private" can't be shared outside this Class</span>

      function __construct(PDO $conn) { <span class="green">// establish the $conn parameter as a PDO datatype</span>
            
            if(!isset($conn))
            {
                  throw new Exception("something went south...:);
            }
            
            $this->cn=$conn; <span class="green">//assign the $conn parameter to the "cn" property</span>

      }      
      
}
      
$pdoConn = new PDO('sqlite:/home/domain/slite0/employees.sql3'); <span class="green">//fully armed and operational database connection</span>
$ myApp = new Application($pdoConn); <span class="green">// PDO is connected outside of Class code and we're now "injecting" that object into the Class where it will be processed and assigned to the "$cn" property</span></span>
OK brucegust, , from what I can tell from that, , you do have good idea about what the application class constructor does and how the parameter of   (PDO $conn) brings in a DB connection (PDO in this), $this->cn to use as a PDO query and such -
       $stmt = $this->cn->prepare('INSERT INTO guests (names, date, sizes) VALUES (:n, :d, :s)');

But do not get to hung up on the terms and concepts for the code workings a developer needs to do for a successful web site Class arrangement and dependency. Just my opinion, , , The "Dependency Injection" theory can be helpful for more complex site builds with many different kinds of operations, where there are many classes and these classes may need to interact and "share" or interface as certain requirements for success are coded into the site. And it may be helpful for smaller things, but Just having a class constructor bring in some external objects, may not mean that the developer was thinking about any site construct rules or theory , but just that she needed some already created interfaces to use in her class.

I'm glad u were able to get some insight.
I think you have grasped it.

I would not declare my classes inside my html code though - in my view a bit of an anti practice - put them in their own file and pass instances to your view where you call members / access properties as needed in the view.
One of the things that I'm coming to realize about some programmers is that they sometimes make things more complicated than they need to be simply because they have the capacity to do so.

Thank you, gentlemen!
just a note, a pet peeve of mine, you say - - "programmers  that they sometimes make things more complicated than they need to"

I find this very true in many coders doing PHP Class Object code, so many here on experts exchange questions and other code sharing sites, seem to try and just copy and paste example code from the manual, or tutorials, and put in two, three or more methods for operations, which I think should be condensed into just a single method, with half the code they use. And many other things, that come from "Thinking" in a function-procedural way for coding, and not looking for or knowing about the benefits of coding and "Programming Thinking" in a connected-interactive OBJECT interface for all site Object connected result way.


Just as a Hint to you, , ,
A thing that many PHP Class code Tutorials leave out of their instructions and examples, is using the (Included with PHP) SPL Interfaces, Classes, Iterators, and Functions. For me, some of these included SPL factors can greatly give extra operations and factors to PHP Class code building, helping to get your Class Object interface more "Understandable", more Efficient, and more Compact.
Unfortunately for developers, there's a long list of different ones, you can see um here in manual -
         http://php.net/manual/en/book.spl.php
One that I have used many, many times, with good results, is the ArrayObject class, which allows a FOR , ForEach, or While LOOP code on  your class Object, and it also has other useful methods and factors. you can see about it here -
       http://php.net/manual/en/class.arrayobject.php
One of the things that I'm coming to realize about some programmers is that they sometimes make things more complicated than they need to be simply because they have the capacity to do so.
You nailed it - and as usual welcome