Archive

Posts Tagged ‘PHP’

Overloading Classes

May 29th, 2010 admin No comments

In OOP, it is a good practice to sometimes “overload” classes if you need to bring in information from the outside. For instance, if you want to include configuration variables in another class, you can “overload” that class with those variables. In this tutorial, I will explain how to do that in both PHP and C++.

Please note, before continuing, that I assume you are an intermediate to advanced C++/PHP programmer. Therefore, I will not go into great detail about how variables are set, etc. because you should already know how that works. We will jump right into the code now for an example as it’s usually the best way to explain these tasks.

PHP

<?php
/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Create our simple class
class OverloadMe
{
/**
* We would like a global var for the whole class
*/
var $var1;

/**
* Constructor
*/
function __construct($name){
$this->var1 = $name;
}

/**
* Name function
*/
function name(){
return $this->var1;
}
}

// Define the name variable
$yourname = "Dennis";

// We overload the function when we initialize it
$overload = new OverloadMe($yourname);

// Now let's get the output
print "Your name is ".$overload->name();
?>

Now, the procedure is very similar in C++, just classes work differently as you already know. I’ll give the C++ code now and explain it all at the end!

C++
src/main.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#include <string>
#include "overload.h"

int main(int argc,char* argv[])
{
std::string name = "Dennis";
OverloadMe overload(name.c_str());
overload.name();
return 0; // exit
}

src/overload.h

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#ifndef Overload_H
#define Overload_H

// Class definition

class OverloadMe
{
public:
// Constructor
OverloadMe(const char* namevar);

// Name function
void name();
private:
// A global var for the class
const char* var1;
};
#endif

src/overload.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Make the class work
#include <iostream>
#include <stdio.h>
#include "overload.h"

using namespace std;

OverloadMe::OverloadMe(const char* namevar)
: var1(namevar)
{
}

void OverloadMe::name()
{
cout<< "Your name is " << var1 << endl << endl << "Please hit enter to exit" << endl;
getchar();
return;
}

Now, for Windows users using MSVC++, this code will compile with a simple copy/paste. For *nix and BSD users, I’ve included a Makefile within the ZIP package for you to use when compiling. Basically, the compiler must compile each item as an object first, then it must compile the objects into the program file rather than compiling the .exe’s directly.

Well, I hope this is of some use to someone. The examples are fairly simple, but should explain the concept easily. As we can see in the C++ example, we initialize the class to a variable, and simply overload that variable at the time of initialization.

Regards,
Dennis M.

Overload_Tutorial

Categories: C/C++, PHP Tags: , , , , ,

Importance of Structure and Coding Etiquette

August 7th, 2009 admin No comments

Well, it’s been a very long time since I last updated and I’d like to apologize to all my subscribers for that. I’ve been very busy, but it seems the work load is going down and I’ll have more time to continue writing! Now, on with the article.

So recently, I have just finished a project where one developer had started and then decided he could not finish the work, so I was hired to finish it. The natural thought to one who is inexperienced is, “This will be a cakewalk. Most of the programming is already done!” – wrong. The first thing that went through my mind was, “I wonder how bad this really is.” So, I accept the project (as I had only a few projects at the time) and take a look.

The code was atrocious to say the least. I felt as if this other developer had never learned how to use comments or his tab key/space bar to format. Most of the time on the project was bent around figuring out what the original developer had tried to do. It was a nightmare.

As I started digging through files and files of unnecessary sloppy code, I thought to myself, “I need to write something about this. This kind of work needs to stop.” I was not upset because of the amateur programming, nor the fact that it was undocumented and poorly written. What bugs me is the fact that someone paid for that kind of work. It looked like the developer copy/pasted everything from snippets he or she found online. That being said, one must learn the importance of structure and coding etiquette.

Structure is important for general organization. It keeps code neat and clean looking and much easier for anyone, to include yourself, to go back and fix errors/security holes. Most people see structural formatting as a simple aesthetic quality when in reality it is like formatting a letter. The structure keeps things organized and understandable on a more universal level.

Coding etiquette, on the other hand, is something learned over a long period of time. No new developer can simply logon and expect to program to the standards set right now, but at the same time should begin mimicking the styles of major developers. Examining the work of others is one of the best ways for any developer to learn, so studying (yes, just like in school) the work of past developers, and prominent works of today, one can easily understand how to program professionally. A simple example would be to write functions rather than hardcode functions multiple times. Or rather than using raw MySQL functions, create an SQL wrapper to execute the functions.

There are many resources on learning how to program professionally, and be neat, but it’s up to developers to use the tools. The vast majority of developers, I would say, hold to the standards. However, for those who do not, they are just ripping off their client in the long-run.

Regards,
Dennis M.

Understanding Arrays and How to Use Them

June 24th, 2009 admin 1 comment

So in a recent project I have just finished up (again, will let you guys know what it is when it’s officialy released), arrays had become my best friend along with some regex, but that’s a topic for another post. I needed to turn strings into arrays, which I would then put back into arrays, and finally back into strings. I did this in a few different ways, but let’s go into some examples of why one would need to do this, then we’ll begin the how; seeing as the how without the why makes very little sense.

Well, I mainly use all this to transfer large amounts of separated data from function to function. In my most recent endeavor it was to split a specific type of file, parse it through 3 different functions (each function returned an array, but dealt with the data in strings which I will explain) then finally took all the information in the provided array and successfully dumped the data to a database. This is only one of the numerous reasons a person could/would use an array, but they help like one couldn’t imagine.

Let’s begin with the basics. For sake of example, we’ll keep things in PHP. The first example below just explains an array. No more, no less.

<?php
// Ways to add data to arrays!
$array1 = array("Entry 0","Entry 1","Entry 2","Entry 3"); // Just put data in
$array2 = array(
0 => "Entry 0",
2 => "Entry 2",
1 => "Entry 1"
); // Define arrays by opening and stating index.
$array3[0] = "Entry 0";
$array3[1] = "Entry 1"; // Enter directly into index

?>

Another way to build an array, more or less indirectly, is to use php’s “explode();” function. This will take text with a defined delimiter and separate each set of data (at the delimiter) into its own index. For example, consider the following.

<?php
$string = "This is a string where we will, use commas, for delimiting the text and to, split this into an, array!";
$array = explode(",",$string);
print "Original: ".$string."<br /><pre>Array: ";
print_r($array);
print "</pre>";
?>

To call these defined arrays we would use $array[INDEX]. Now, there are many ways to access this data and filter it. Let’s begin by calling one value from an array.

<?php
$array = ("Entry 0","Use this text","Entry 2","Entry 3","This text isn't being called either");
print $array[1];
?>

The script above with print “Use this text” because it is in the array at the index value 1. It is important to remember that indexes start at 0 unless defined otherwise. Now, we’ll explain some more intricate ways of getting all your values. The first way is iteration using the “for();” loop. Here goes:

<?php
$array = ("Test","Test2","Word3","Keep 'em coming!","white space next :P ","","No need for that","We <3 trim");

// Iterate.
for($i=0;$i<count($array);$i++){
print $i.") ".$array[$i]."<br />";
}
?>

Now this will just result similarly to the foreach(); which I am about to explain. However, sometimes iteration is more effective than foreach(); because it gives you more liberty. Most of the time I would recommend iteration for multi-dimensional arrays (arrays within arrays and so on), but usually two different ones. For example:

<?php
$array = array(array("Array in index","number 0"),array("Array in index","number 2"));

for($i=0;$i<count($array);$i++){
// Now, let's get our multidimensional values! :D
for($ii=0;$ii<count($array);$ii++){
print "[".$i."][".$ii."]: ".$array[$i][$ii]."<br />";
}
}
?>

Now, that will grab all the data within the arrays within the arrays. Wow, sounds confusing, but once you get a better grasp, it’s really quite simple, but I cannot lie; it all seems very daunting at first. Now we’ll explain the foreach(); function. This function basically does what we just did manually, but sometimes is easier and more effective. A lot of times, you will use the two in conjunction (even if for different purposes), so become friendly with both of them!

<?php
$array = array(
0 => "Entry 0",
1 => "Another entry",
2 => "Again...",
3 => "And finally :P "
);

foreach($array as $key => $value){
print "Key/Index: ".$key.": ".$value."<br />";
}
?>

From the code above, you can see that the foreach(); function has accomplished the same feat we did earlier with iteration. On a simple array such as this, it would be best to use foreach, but like I said: it may be necessary at times to use iteration.

As I mentioned earlier, both can be used in conjunction. Just a quick example (we won’t go through the actual coding of it) is if you have a multi-dimensional array where you feel the need to use foreach, you can use foreach($var[$i] as $key => $val){} and work it that way.

So all in all, everything boils down to: love iteration, love foreach(); on the programming languages it’s available, and above all LOVE arrays! They are right next to regex in the developer’s “most useful tools” section of his or her tool belt!

Regards,
Dennis M.

Categories: Other, PHP Tags: , , , ,

PHP & Pagination

June 4th, 2009 admin No comments

Very often I see people asking questions about this on forums such as DP and NP. I have probably posted my code snippet on how to efficiently create a simple pagination document more times than I can count (which whether you believe it or not is pretty high ;) ). So I decided I’d go through it here.

First off, we’ll explain what pagination is. You may be reading this article not even certain if pagination is what you need. However, if you have multiple MySQL results you wish to organize and display “x” results per page, you’re on looking at the right thing. It is as simple as that. Pagination is really just web jargin used to shorten up “return results only displaying ‘x’ per page.”

So, I’m going to post the snippet and I’ll go into it a little bit, but I do believe that the comments explain pretty thoroughly. First the database structure we’re going to use ;)

CREATE TABLE `pagination` (
`id` BIGINT( 10 ) NOT NULL ,
`name` VARCHAR( 32 ) NOT NULL ,
`content` TEXT NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;

And now.. The moment we’ve been waiting for… The actual pagination script! :)

<?php
/**
* Pagination Script by Dennis M.
* (C) 2009 Dennis M. All Rights Reserved.
*
* Primary purpose of this script is to teach
* people the art and concept of pagination
* and how to effectively create/use it.
* Please give credit to Dennis M. if you
* take anything directly from this script.
*
*/

// Connect to DB
mysql_connect("localhost","USER","PASS");
mysql_select_db("USER_DATABASE");

// Define results per page
$perPage = 1;

// Define page number in URL
$num = $_GET['no'];

// Define link starting point.
$linkno = 1;

// If no number given, default it.
if(!isset($num) OR !is_numeric($num)){
$num = 1;
}

// Multiply to see where we're at to show results :)
$currentLimit = $perPage*($num-1);

// Get how many pages we'll have total (for links)
$numPages = mysql_num_rows(mysql_query("SELECT * FROM pagination"))/$perPage;

$query = mysql_query("SELECT * FROM pagination ORDER BY id ASC LIMIT ".mysql_escape_string($currentLimit).",".mysql_escape_string($perPage).";");

// Fetch all the info
while($row = mysql_fetch_array($query)){
$title = stripslashes($row['name']);
$article = stripslashes($row['content']);
?>
<html>
<head>
<title>Pagination Test</title>
</head>
<body>
<h1><?php echo($title); ?></h1><br />
<p><?php echo($article); ?></p><br /><hr>
<?php
}
print "<p align=\"right\">";
if($perPage <= 2){
while($links < round($numPages)){
?>

<?php
$links++;
$linkno++;
}
} else {
while($links <= round($numPages)){
?>

<?php
$links++;
$linkno++;
}
}
?></p>
</body>
</html>

Now that’s all there really is to it. Basically how it works is it updates the SQL query depending on the page number (received from $_GET['no']). If none is defined, it reverts to the default and all goes accordingly!

Pagination Tutorial

The download link is above as usual! :) Enjoy

Regards,
Dennis M.

PHP vs Ruby on Rails (RoR)

June 2nd, 2009 admin 4 comments

Well people have been asking me lately about this Ruby on Rails (RoR). I often receive questions such as “What is RoR?” or “Is it better than PHP?”. Well, Ruby on Rails is another web programming language, but is not widely compatible across all web servers, but is increasingly becoming so. Personally, I am more of an advocate to PHP, but we’ll try to get the facts straightened out.

To begin, I’m going to assume everyone knows the basics of PHP. It’s fast, efficient, integrated with the webserver, etc. But for those of you completely unfamiliar with Ruby on Rails it is made by the “Ruby Core Team” (of the Ruby Programming Language). The format of the language is similar to Python if any are familiar with that. Ruby generally runs on its own server, separate from the general webserver-to my experience anyway.

So now that we have the basics down about each let’s go over the weak points in each and strong points. We will begin with the weak points to Ruby on Rails. Since it runs on it’s own server, it makes it more difficult to readily integrate with a site: obviously. Also, for those of us who prefer the nice C/C++ style programming, you can forget it with RoR. You will definitely end up using “end” much more than you would care to admit with this language. Compatibility across servers is more or less low. Most servers do not provide the RoR service, so that is also a downfall of RoR.

Likewise, PHP also has its faults. Since the language is so widely used and installed on practically every serer on the web, it allows for more holes to be more easily and quickly found. This means more frequent updates (which could be good if it does not become a nuisance) and since it is integrated with the web server, that also means long patch times. Depending on how you have setup PHP, you may even have to recompile the webserver. Normally it doesn’t cause a great problem for most servers because the old version doesn’t remove until the new version is finished compiling, but it greatly increases server load. For webhosts, this could cause a problem because this means that they have to go down for more server maintenance time. Also, unfortunately for PHP, every time one wants to add a new feature (example add ziplink support or something) they would have to recompile PHP.

Although both have their faults, both also have very strong points. Again, we’ll begin with RoR. RoR, again, since it’s not integrated means little downtime if it needs to be updated. Also, it is similar to Perl in the respect that it can download modules quickly and easily. Ruby, growing more popular, also is easier for users who are entering programming. It definitely scores an A+ on the entry level programming language level and pretty powerful with simple code.

PHP, on the otherhand, though a little more complex has its key aspects. There is mass compatibility with PHP. As mentioned earlier, pretty much every server on the web is PHP enabled. It has become the web standard over the years. Another benefit, since most open source software is programmed in PHP, is one who knows it can make their own program modifications and customizations to most open source programs. Above all, the support over the web is great because users all over the web have a deep understanding and knowledge of the language and are willing to offer free help on forums all over the web.

So all in all, both languages have their ups and downs. Ultimately, it is your choice to decide which you would rather learn/install on your server. Peronsally, I would go with PHP simply because it’s more available and there is a greater user base to help you. If you are looking for custom projects to be made, it may also be much easier to find a programmer to do work for you if you’re looking for PHP. But if you have never looked at programming before and cannot seem to grasp the concepts of PHP, Ruby may be a good alternative to start learning how programming should look and feel.

Regards,
Dennis M.

Categories: Other, PHP, Software Reviews Tags: , , , ,