Jump to content

OOP ... Creating Object and Calling Function in One Shot?


947740

Recommended Posts

Hey guys!  I just learend object-oriented programming today (and absolutely love it), so please excuse me if I don't know some of the obvious things. :)

 

Anyways, I have two classes:

 

class Connection {

public function connect() {
// Variable data removed //
$this->cxn = mysqli_connect($host, $user, $pword, $db);
return $this->cxn;
}
public function unConnect() {
unset($this->cxn);
}
}
class Query {

public function doQuery($query) {
$e = new Error();
$cxn = new Connection(); // This line
$connection = $cxn->connect(); // This line
$this->query = $query;
$this->result = mysqli_query($connection,$this->query) or $e->setError(mysqli_error($connection)); // And the $connection variables in this line
$e->checkError();
echo $e;
}
}

 

My main question are about the commented lines

 

Hopefully I can word this right...but I would like to create the object Connection and call the function connect() at the same time.  In other words, I don't want to have to make the variable $cxn, and then make another variable $connection to use in the $this->result line.

 

I have one thought that I could do a __construct() function in the connection class...but i'm not quite sure how to achieve that effect.

 

Any help would be greatly appreciated. :)

Link to comment
Share on other sites

Hey guys!  I just learend object-oriented programming today (and absolutely love it), so please excuse me if I don't know some of the obvious things.

 

Pardon me for saying so but OOP isn't something you learn in one day. Just because your using classes, does not mean your programming in OOP.

 

A __construct cannot return a value so, if you want your connection returned, you will need to do it as is. Another option however might be to make the Connection object a singleton.

 

Seriously though, the way your code is currently is VERY inflexible as your Query class is tied to the Connection class. Is there a particular reason you think these need to be two separate classes?

Link to comment
Share on other sites

Pardon me for saying so but OOP isn't something you learn in one day. Just because your using classes, does not mean your programming in OOP.

 

My choice of words was obviously inadequate in describing the situation.

 

I suppose there is no particular reason why I separated the classes...initially it seemed as connecting and querying were two separate entities and therefore deserved to be separate.  Perhaps my logic is flawed.

Link to comment
Share on other sites

MySqli already has an OOP interface so I don't see the point in wrapping it again within your own implementation unless of course you have a certain interface you need to implement (but I doubt your up to that yet).

Link to comment
Share on other sites

You can create two different classes in that one class can inherit the other.

 

Class connectable

{

}

 

Class Query extends connectable

{

}

 

check out inheritance if you love oop.

http://php.net/manual/en/keyword.extends.php

 

If I were to make query an extension of the connection class, would that not serve the same purpose of combining the two classes (in this particular instance)?  And it would seem Thorpe is right in the matter that I won't need to use the connection class outside of querying, so I might as well combine them...

Link to comment
Share on other sites

If your going to have calls to mysqli* functions within your Query object you may as well combine these two objects into one as you have already lost all flexibility.

 

What is the point of these classes exactly is what I'm getting at. I understand its likely just a learning oversize but still, there is no point in simply wrapping things in classes for no apparent reason.

Link to comment
Share on other sites

My reasoning was that I can now perform queries and get results back in two lines of php code...I can error check, validate data, perform the query, etc all in the classes, all the while cleaning up the view pages.

 

Again, doing too much within your classes methods prevents flexibility. Classes should be made as flexible as possible so that they can be re-used from project to project. Error handling should still be handled in client code because it may need to be handled differently from project to project.

Link to comment
Share on other sites

You can create two different classes in that one class can inherit the other.

 

Class connectable

{

}

 

Class Query extends connectable

{

}

 

check out inheritance if you love oop.

http://php.net/manual/en/keyword.extends.php

 

I don't see how a query is-a connection besides:

 

* favor composition over inheritance

 

class Query {

  public function __construct(Connection $c) {

    $this->cxn = $c;

  }

}

 

Ofcourse after he applied:

 

* program to an interface, not an implementation

Link to comment
Share on other sites

You don't need a Connection class though. You are thinking to narrow. Your ultimate goal is to retrieve data from the tables, this should be your starting point. Why? Because if you model your application from that point you will be able to easily modify (extend) it's design to meet new goals: retrieve data from an xml file, retrieve data from a service, ...

 

Your goal should be to model retrieve data from and let the client fill in the blanks.

Link to comment
Share on other sites

Don't try to go for that one line of index code. Although you can do it though and conform to oop principles eg, create a class that is your current project, that is sort of like the brain that tells the classes what to do.

 

But you dont really need to do that, just think - Classes are portable pieces of code. they should be able to plug in to any other framework you will/have/can develop. Its meant to save you time in the long run - it adds a lot of code time in the short term until you dont have to write database connections, error handling/ logging/authentication etc etc.

 

Have a real good think about it, design your oop project if you want it to be true oop. Because if a class has a another (specific) class dependancy, i think you've done it wrong.

 

and as ignace said, you dont want 100's of classes that depend on each other, you want a single class that does its job, eg, a Data Class, Authentication Class, Error Class etc.

 

-cb-

Link to comment
Share on other sites

Okay, I think I understand what you guys are trying to get across.  Most tutorials I've found online don't cover that kind of stuff. ;)

 

You all are making the point that flexibility is real important and that having classes that don't require other classes is preferable.  I'm going to throw an example out here just to see if my thought here is valid.

 

Right now my error class allows me to set an error.  It's rather generic, and I can obviously create new functions in the relevant class to redefine a function if need be.

 

class Error {

public function setError($error) {
$this->error = "There was an inescapable error: " . $error;
}
public function unError() {
unset($this->error);
}
public function getError() {
return $this->error;
}
public function checkError() {
	if(!isset($this->error)) {
	// If no error is set, set error = to a success statement
	$this->error = "The task was completed successfully.";
	}
return $this->error;
}
public function __toString() {
return $this->error;
}
}

 

I'm almost starting to think that I'm relying on classes too much.  Either that or my logic is flawed.  I think responses on this class will finalize my thoughts on the matter...

Link to comment
Share on other sites

Well, for one, you should have defined the variable $error before calling it out of the blue.

 

On to the more important aspect, that error class is useless and not at all flexible. It does one thing and one thing only, which means I don't need a class for it. It'll be shorter to just write the error myself. What's the point of your error class? To temporarily store an error message? You have to think about design and what functionality you want the class to have. I mean, what's the point of storing one error message? I can do that in a variable.

 

On a side note, why should I have an instance of an Error object to use it? Seems weird.

Link to comment
Share on other sites

Well, for one, you should have defined the variable $error before calling it out of the blue.

 

On to the more important aspect, that error class is useless and not at all flexible. It does one thing and one thing only, which means I don't need a class for it. It'll be shorter to just write the error myself. What's the point of your error class? To temporarily store an error message? You have to think about design and what functionality you want the class to have. I mean, what's the point of storing one error message? I can do that in a variable.

 

On a side note, why should I have an instance of an Error class to use it?

 

I see what you are saying...and on top of that, an error really does not have many properties, does it?  That would be the point...you want a class for something with many different properties that need to be dealt with...not just one value.

 

It seems I got a bit too, er, class-happy.

Link to comment
Share on other sites

I don't think you have a clear grasp on what should go into a class. I mean, it's good to have an error handling class, but the one you presented is a bit useless.

 

- What if I have multiple errors?

- Why have two methods that return the same value? (getError and __toString)

- Why set an error message to some success string?

- Why are part of the error strings hard-coded? That means it's harder to change the value when you need to change the display right?

- What's the purpose of checkError? It returns the error string. I would have guessed that it returns a true or false value instead. It also doesn't make sense because that method also writes a value to the error string. One method should do one thing. You're doing too much.

 

I suggest that before you create a class, ask yourself what the point of the class is. What can it do? How useful is it? The usefulness of a class also depends on how you set it up. As everyone else mentioned, you need to think more abstract and more organized in how you set things up.

Link to comment
Share on other sites

Okay, it's obvious I need to think more abstractly.  I'm trying to code before thinking...it needs to be the other way around.  I should probably read up on the theory a bit more.  I mean, I can obviously write classes and functions and make them work just fine, I just don't have a good enough understanding of the theory.

 

Thanks to everyone who replied.  I will take as much as I can from you guys, learn, and then come back with some code that actually is feasible.

Link to comment
Share on other sites

I see what you are saying...and on top of that, an error really does not have many properties, does it?  That would be the point...you want a class for something with many different properties that need to be dealt with...not just one value.

 

It seems I got a bit too, er, class-happy.

 

There are languages where everything is an instance of some class or another. If creating a class of of something gives you additional (re)usability or flexibility, you should not care how many properties it has.

Link to comment
Share on other sites

Check out the OOP articles on this website. They are pretty good.

http://www.phpfreaks.com/tutorials

 

Other than that:

http://oreilly.com/php/archive/mvc-intro.html (This is ore what your end result should really be aimed towards imo)

http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html

 

Are a couple of decent OOP articles.

Go more for the articles that explain the concept, rather than give you tons of (absolutely useless) code examples.

 

-cb-

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.