473,396 Members | 1,907 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

OOP Style coding

Tarantulus
114 100+
hi guys,

I've recently begun working with OOP concepts, and I grasp the class/method setup well enough, however, my code hasn't followed my brain, and tends to be still very static and inflexible.

for example (not a real example):

Expand|Select|Wrap|Line Numbers
  1.  class sqlstuff{
  2.  
  3. function insert($vals){
  4. $sql="insert $vals[1],$vals[2],$vals[3] into tblname col1,col2,col3";
  5. $action=sql_query($sql);
  6. }
  7.  
  8.  
using the example, could you point me in the right direction?
May 28 '08 #1
6 1817
rpnew
188 100+
hi guys,

I've recently begun working with OOP concepts, and I grasp the class/method setup well enough, however, my code hasn't followed my brain, and tends to be still very static and inflexible.

for example (not a real example):

Expand|Select|Wrap|Line Numbers
  1.  class sqlstuff{
  2.  
  3. function insert($vals){
  4. $sql="insert $vals[1],$vals[2],$vals[3] into tblname col1,col2,col3";
  5. $action=sql_query($sql);
  6. }
  7.  
  8.  
using the example, could you point me in the right direction?
What do you want to do exactly??
Do you want to make your INSERT statement flexible??

Regards,
RP
May 28 '08 #2
coolsti
310 100+
Hi,

first of all, your class seems to be missing a constructor, which must be a function which has the same name as the class. But maybe you just are not showing this in your example.

After you create a class, there are two ways to use it: by instantiating (creating) an object assigned to a php variable, or by directly calling the class function. In the latter case, you cannot use the $this within the function you are calling, but this allows you to use a class function without creating an object, and is a good way of "namespacing" your code.

Like if you have a class called "myclass" and in it is a function called "myfunction" with let us say no arguments but returns a value, you can call it like this without creating an object:

Expand|Select|Wrap|Line Numbers
  1. $result = myclass::myfunction();
  2.  
But what you really want to do most of the time is to create an object as a PHP variable like with:

Expand|Select|Wrap|Line Numbers
  1. $myobject = new myclass();
  2.  
where here for an example the constructor does not take any arguments (but it can if you make it so).

This way, if there are any class member variables, they can be accessed within the class as $this->membervariable and externally to the class as $myobject->membervariable (this is why PHP is so flexible). And you access class functions in a similar fashion.

This is just a few words to get you started. Look up what I am writing about in the PHP class documentation.

No time to write more. Hope this helps a little.
May 28 '08 #3
Tarantulus
114 100+
ok, the example was just that, an example, but I've not looked into constructors... maybe what I'm doing isn't really OOP...

as for what I am trying to do, in the example you are correct, it would be attempting to make that function more flexible, but it was more of a leading question into learning more about OOP as all of the resources I can find already assume knowledge of OOP or are EXTREMELY basic (aimed at people who have never written a line of code in their lives).

Thanks for the pointers so far!
May 28 '08 #4
pbmods
5,821 Expert 4TB
Heya, Tarantulus.

This should get you started -- or get you more confused. Either way, enjoy the journey.

When you develop for OOP, you will want to think in terms of objects (generally known as 'models' when they relate to database records), rather than tasks or functions.

For example, suppose you had a program to fetch and edit customer data. In procedural style, you might come up with something like this:

Expand|Select|Wrap|Line Numbers
  1. function fetchCustomer( $customerID )
  2. {
  3.     global $db;
  4.  
  5.     $res = mysql_query("SELECT * FROM `Customers` WHERE `CustomerID` = '{$customerID}' LIMIT 1", $db);
  6.  
  7.     return mysql_fetch_assoc($res);
  8. }
  9.  
  10. function saveCustomer( $name, $title, $phone, $customerID = null )
  11. {
  12.     global $db;
  13.  
  14.     mysql_query("REPLACE INTO `Customers` SET `Name` = '{$name}', `Title` = '{$title}', `Phone` = '{$phone}', `CustomerID` = '{$customerID}'", $db);
  15. }
  16.  
Let's change this up and make it object-oriented. So we have a Customer, which has certain properties, such as an ID, title, phone number, etc. The Customer can do certain things, such as saving its properties to the database. We can also do certain things related to Customers, such as fetching one from the database.

The distinction between those last two is important because saving a Customer requires that we already have an existing Customer, whereas fetching a Customer requires that we don't.

A skeleton of our Customer object might look something like this:
Expand|Select|Wrap|Line Numbers
  1. class Customer
  2. {
  3.     public $myCustomerID;
  4.     public $myName;
  5.     public $myTitle;
  6.     public $myPhone;
  7.     // Yada yada....
  8.  
  9.     public function __construct( $customerID, $name, $title, $phone )
  10.     {
  11.     }
  12.  
  13.     public function save(  )
  14.     {
  15.     }
  16.  
  17.     public static function load( $customerID )
  18.     {
  19.     }
  20. }
  21.  
Here's the class with its methods implemented:
Expand|Select|Wrap|Line Numbers
  1. class Customer
  2. {
  3.     public $myCustomerID;
  4.     public $myName;
  5.     public $myTitle;
  6.     public $myPhone;
  7.     // Yada yada....
  8.  
  9.     private $_myDB;
  10.  
  11.     public function __construct( $db, $customerID, $name, $title, $phone )
  12.     {
  13.         $this->myCustomerID = $customerID;
  14.         $this->myName = $name;
  15.         $this->myTitle = $title;
  16.         $this->myPhone = $phone;
  17.  
  18.         $this->_myDB = $db; 
  19.     }
  20.  
  21.     public function save(  )
  22.     {
  23.         mysql_query("REPLACE INTO `Customers` SET `Name` = '{$this->myName}', `Title` = '{$this->myTitle}', `Phone` = '{$this->myPhone}', `CustomerID` = '{$this->myCustomerID}'", $this->_myDB);
  24.     }
  25.  
  26.     public static function load( $db, $customerID )
  27.     {
  28.         $res = mysql_query("SELECT * FROM `Customers` WHERE `CustomerID` = '{$customerID}' LIMIT 1", $db);
  29.  
  30.         if( $row = mysql_fetch_object($res) )
  31.         {
  32.             return new Customer($db, $row->CustomerID, $row->Name, $row->Title, $row->Phone);
  33.         }
  34.         else
  35.         {
  36.             return false;
  37.         }
  38.     }
  39. }
  40.  
This is a very, VERY basic implementation, and I promise you that in five years, your DB models will look nothing like this, but it is a good start.

Let's look at a common situation: Changing a customer's name.

Here's how you would do it using procedural code:
Expand|Select|Wrap|Line Numbers
  1. $customerID = 5;
  2. $newName = 'Frank Thomas';
  3.  
  4. // Fetch the customer's info.
  5. $customerInfo = fetchCustomer($customerID);
  6.  
  7. // Change the info.
  8. $customerInfo['name'] = $newName;
  9.  
  10. // Save the info.
  11. saveCustomer($customerInfo, $customerInfo['Title'], $customerInfo['Phone'], $customerID);
  12.  
Here's how you would do it with objects:
Expand|Select|Wrap|Line Numbers
  1. $customerID = 5;
  2. $newName = 'Frank Thomas';
  3.  
  4. // Fetch the customer's info.
  5. $Customer = Customer::fetch($db, $customerID);
  6.  
  7. // Change the name.
  8. $Customer->name = $newName;
  9.  
  10. // Save the info.
  11. $Customer->save();
  12.  
May 29 '08 #5
coolsti
310 100+
Excellant example by pbmods!

A few things to note when you compare that example's procedural vs. OOP code: The OOP code makes things more organized, as things that "belong" to a customer are located as a variable or method within the customer class, and is referred to either directly with the classname::classmember syntax or by the $classobject->classmember syntax. In other words, you now know where to find things that belong to this particular object that is being modelled in your code.

But another aspect of OOP that is very valuable is the way that code can be made re-usable or flexible. Take this example: Let us say we have two things that are very different, let us say an object "dbdata" that needs to be stored in a database, and another object "filedata" that needs to be stored in a file on the hardisk. So if you imagine that you write a class for each object, and for each object you write a member function that does the appropriate save and then call it with a common name, for example "saveData()".

Expand|Select|Wrap|Line Numbers
  1. function handleData($dataitem) {
  2. // do some things here to the data. 
  3. // now you need to save the data.
  4. $dataitem->saveData();
  5. // do other stuff maybe
  6. }
  7.  
  8. $myfiledata = new filedata();
  9. $mydbdata = new dbdata();
  10. // do stuff here
  11. // handle the data for each object
  12. handleData($myfiledata);
  13. handleData($mydbdata);
  14.  
The point here is that each class knows how to save its data because of its own class method. Each class has its own set of methods to do whatever tasks are needed, but in a manner that is appropriate for that class. But externally to the class, the code can look the same. You then begin to be able to code much cleaner, and more concise.

If you were to do this procedurally, you could do some tricks (you can have specific save functions for each object and send the name of the save function to call as an argument to the above "handleData" function, for example) or you would need to add arguments to a common save function to tell the function how to save the data depending on which object it is called for. But this is sloppy and can easilly lead to very confusing code.
May 29 '08 #6
Tarantulus
114 100+
Wow, suddenly it all makes sense, that was an awesome example. It shows me that what i thought was oop was simply not right! Thank you so much.
May 29 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

22
by: beliavsky | last post by:
Is there a more recent set of Python style guidelines than PEP 8, "Style Guide for Python Code", by van Rossum and Warsaw, at http://www.python.org/peps/pep-0008.html , which is dated July 5, 2001?
3
by: Sara Khalatbari | last post by:
Hi! Suppose you're writing a module & writing the definition of each function in that module in " or """. for example: a) "This function does this & that" or: b) """This function does blah...
31
by: bart | last post by:
Why is it that everybody likes the follwowing curly braces syntax function() { implementations; } I find the following much better to read (C style) function() {
16
by: E. Robert Tisdale | last post by:
C++ Programming Style Guidelines http://geosoft.no/development/cppstyle.html I think that these guidelines are almost *all* wrong. For example: 11. Private class variables should have...
18
by: craig | last post by:
I am curious about how many of you prefer style 1 vs. style 2, and why. Are there names for these style? style 1: method { }
31
by: Christopher Benson-Manica | last post by:
How about your if/else if/else constructs? Being nitpicky like any good C programmer, I'm in the process of transforming code written like if( cond ) { ... } else if( some_other_cond ) {...
144
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this...
39
by: jamilur_rahman | last post by:
What is the BIG difference between checking the "if(expression)" in A and B ? I'm used to with style A, "if(0==a)", but my peer reviewer likes style B, how can I defend myself to stay with style A...
100
by: Angel Tsankov | last post by:
Can someone recommend a good source of C/C++ coding style. Specifically, I am interested in commenting style and in particular how to indent comments and the commented code, rather than when to...
1
by: rbaulbin | last post by:
Hello - Does anyone know if of a utility that can traverse an HTML file for all inline CSS style tag occurrences and generate an external style sheet from them, and then create (intelligent?)...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.