Excellent PHP Tips/Tricks/Techniques To Follow

Status
Not open for further replies.

Aequitas

New member
Feb 19, 2007
2,954
73
0
Canada
Well as a programmer all these aspects I'm going to be talking about are common sense to me but it has been brought to my attention that the aspects I'm going to cover here are not all that well known among less advanced programmers.

That mixed with no sticky thread in this section and no real talk about this important aspect on WickedFire is why this thread is going to be created, by the end of this thread you'll know how to better optimize your code and to avoid bad coding practices. Also if you have any coding questions after words please let me know and I'll do my best to answer them and if you want to contribute some more then please do so.

I'll simply start off with the basics of any programming language, it doesn't matter what type of language you are using these are common among all languages and those are common coding practices. Just like in the medical field where doctors need a standard form of communication and diagnosis the programming world is much the same.

The first common practice are comments in your code, lots and lots of meaningful comments are helpful for both you and others reading your code, the comment structure varies depending on which language you are using but for PHP see the code below for an example of proper comment practice.

Code:
[B]Example A:[/B] 
// Creates cURL bot
$bot = new bot();

[B]Example B:[/B] 
/* Stores number of pages in $pages */
$pagesExp = "(?<=Page [\d] of )[\d]*";
$pages = preg_match_all("#".$pagesExp."#",$source,$feeders);
Looks easy right well actually Example A isn't required and as you get better in coding you'll realize why, first off Example A has a line comment (because of the //) but the comment isn't required because its a very simple line that almost every PHP programmer will know what it does when they look at it, so no need to waste your writing time with commenting everything.

Now Example B on the other hand isn't so obvious and requires a comment because not everyone looking at it is going to understand why your doing the expression. Also note that I used a block comment in this one which is depicted by the opening /* and closing */.

Easy and boring stuff right? Well it can save you hours on a big project so over commenting isn't required but complicated blocks of code or complicated lines of code need to be commented for both you and someone else looking at it, if you don't comment your code I can guarantee you that going back to it a month later you won't know why the hell you did what you did.

So thats beyond basics just so everyone knows but lets move onto some better stuff like block format and organization then I'll move onto code optimization.

First off in PHP and many other languages whitespace doesn't mean anything and should be used correctly, for instance which block of code can you read better?

Code:
[B]Example A:

class bot
{
    function setup()
    {
        $cookieJar = 'cookies.txt';
        curl_setopt($this->curl,CURLOPT_COOKIEJAR, $cookieJar);
        curl_setopt($this->curl,CURLOPT_COOKIEFILE, $cookieJar);
        curl_setopt($this->curl,CURLOPT_AUTOREFERER,true);
        curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION,false);
        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true);
    }
    function get($url)
    {
        $this->curl = curl_init($url);
        $this->setup();
        return $this->request();
    }
    
    function request()
    {
        return curl_exec($this->curl);
    }
    
    function kill()
    {
        curl_close($this->curl);
    }
}


Example B:

class bot
{function setup(){
        $cookieJar = 'cookies.txt';
        curl_setopt($this->curl,CURLOPT_COOKIEJAR, $cookieJar);
 curl_setopt($this->curl,CURLOPT_COOKIEFILE, $cookieJar);
        curl_setopt($this->curl,CURLOPT_AUTOREFERER,true);
        curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION,false);
        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true);}function get($url)
    {$this->curl = curl_init($url); $this->setup(); return $this->request();
    }function request()
    {return curl_exec($this->curl);
    }function kill()
    { curl_close($this->curl);
    }
}

Example C:

class bot
{


    function setup()


    {


        $cookieJar = 'cookies.txt';

        curl_setopt($this->curl,CURLOPT_COOKIEJAR, $cookieJar);

        curl_setopt($this->curl,CURLOPT_COOKIEFILE, $cookieJar);

        curl_setopt($this->curl,CURLOPT_AUTOREFERER,true);

        curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION,false);

        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true);

    }


    function get($url)
    {


        $this->curl = curl_init($url);

        $this->setup();

        return $this->request();

    }
    
    function request()
    {

        return curl_exec($this->curl);

    }
    
    function kill()

    {
        

curl_close($this->curl);


    }


}[/B]
In the computers eyes all these code blocks will execute at the same amount of time and it doesn't matter but to human eyes Example B is just stupidly hard to read and Example C is also way too spaced out to read correctly but Example A is just right, so again use whitespacing in moderations and don't get carried away, again very simple stuff.

Ok enough simplicity if you need simple answers then ask later on and I'll respond but what I want to get into right now is PHP code optimization which a lot of noobs seem to fail so badly and the worst part of it is that they won't ever realize it until they begin to write larger programs because lets face it you can code a small program as shitty as you want and it will still run pretty damn fast but continue to build on that shitty code and you'll spend months going back over it trying to speed it up.

The first example is when using Functions in PHP now functions dramatically decrease the speed in which your scripts will run, however functions are a powerful and are still needed, if I remember correctly functions will actually slow down your code by 33% overall. So for each function you clean up you'll speed up the execution time of your code by 33% that is huge.

One common mistake I see people making is using functions too much look at both these below examples.

Code:
[B]Example A:

function stripUrl(){
    $urlExp = "";
    preg_match_all("#". $urlExp ."#",$url,$strippedUrl);
    return ($strippedUrl[0][0]);
}


function LinkingArrays(){
    for($i=1; $i<($pages + 1); $i++){
        $appendedUrl = $url."?p=".$i;
        array_push($linkArray,$appendedUrl);
    }
}[/B]
That seems clean, organized and nice right? Well no its not if your using these functions over 100 or so times in your code then yes by all means do this but even still I recommended you don't. The reason for this is simple, it only takes you at most 10 seconds longer to write out these few lines of code when needed in your application then it is to just call the function.

But by taking an extra 10 seconds to write out a few lines when needed (Even though it may seem repetitive), it will speed up your code by 33% each time you don't use the function. Also remember that in PHP things like the example below are also functions, they are just pre-build by PHP and you never see the full function code for them.

Code:
[B]count();
array();[/B]
So when do you use functions? Well this changes with personal preference but I like to only use additional functions when there are more then 20 or so lines of code which need to be called several times over in an application, this speeds up the time I need to write out the code, it cleans up my code, and even though I still sacrifice a bit of speed its not enough to justify not using the function. So with practice and experience you'll begin to find a balance between execution speed and the time it takes to write the code.

The next optimization tip I want to talk about is incrementing items in your code, this is done for so many reasons in almost every application a person could write, there are basically two ways to increment, one is known as pre-increment and post increment, look at the example below.

Code:
[B]Pre-Increment:
++$i;


Post Increment:

$i++;[/B]
Now this is something PHP specific so don't try to use this on other languages but the pre-increment is a tad bit faster then the post increment and the reason for this is because that post increment actually create a phantom variable which stores the new value but pre-increment does not and it changes to value of the variable directly. You should also be careful when using the pre-increment in loops because incrementing something too early will cause the formula to be off by 1 as where post increment will be exact, so this is just something to keep in mind.

Here is yet another thing that becomes complicated for noobs and that is using print(); over echo(); well guess what they both do the exact same things right? They print out code to the browser or screen.

The answer is yes and no but for optimization sake echo(); is faster then print(); because the print function can return to you a status of success or not while the echo function will simply display the text and nothing more.

All this is something that comes with practice and there are a ton of more stuff that I'll have to add to this at a later date but by keeping some of these tricks in mind you'll be able to build much bigger and much faster functions.

P.S. Regular Expressions (REGEX) are extremely slow and are not recommended if a string alternative is available but I'll talk about that later on.
 


Wow I passed. Good points to keep in mind when you're coding. :)

Funny you mention the whitespace deal...that is pet peeve of mine and if I get some code from someone like that...I spend a good hour just straighting it out so I can read it. (depending on size)
 
Wow I passed. Good points to keep in mind when you're coding. :)

Funny you mention the whitespace deal...that is pet peeve of mine and if I get some code from someone like that...I spend a good hour just straighting it out so I can read it. (depending on size)

Same with me man then I found a cool little thing in PSPad which enables you to auto-format HTML and PHP. It could be a touch better editing but it saves a million hours if you've got bad code to go through.
 
I was going to ask, what you people recommend for PHP programming? Especially for someone TRYING to learn (hangups).

A couple that were recommended to me were:
phpDesigner 2007 Professional
Zend Studio

What does everyone use?
 
I was going to ask, what you people recommend for PHP programming? Especially for someone TRYING to learn (hangups).

A couple that were recommended to me were:
phpDesigner 2007 Professional
Zend Studio

What does everyone use?

Honestly I make thousands off my programming and I do it all from a freeware piece of software known as PSPad.

I've looked into Zend Studio but the price isn't worth it unless your going to be doing some major projects, I'm talking like huge web applications that are going to be used by hundreds of thousands of people just web sites are not worth the price.

Sure you can get other Zend Goodies (Keep in mind PHP is Zend and Zend is PHP) like the Zend optimizer, obfusecator but again you only really require that for big ass projects, which trust me can be big pains in the ass as well.

I've used phpDesigner 2007 Professional and the only quality I liked about that over PSPad is not having to install a seperate debugger you can view everything from your page right away but the way it shadows your code when working is a pain in the ass for a lot of reasons.

I like PSPad simply because its free, it was made specifically for PHP, it has a ton of useful built in tools like the reformat option, excellent option, you can get tons of other free additional plug-ins for it like spell checker for your HTML, so many good uses and the color coding in my opinion is one of the best.

Heck you can even get a tele support plugin for it and its easy to use and learn.
 
What does everyone use?

I use vi for everything. You can even install ctags for PHP (I don't use it though). I'm so used to vi I have to install it on my windows boxes. I can't even use notepad now without pulling my hair out.

If you don't know vi then this post is probably useless to you. Yes, I am an addict...
 
Great post, didn't realise functions slowed things down that much. Will def bare that in mind.

I use php designer (free from any good torrent site ;)) - it's great for php noobs as it lets you quickly and easily look up stuff (php.net library built in). The debugger is really useful too.
 
I use notepad++ for all my coding. Anyone have any experience with this and know if anything else - like php designer, pspad etc - is better?
 
I use vi (vim actually) for all of my HTML and PHP programming. I do use PSPad sometimes, but since I'm usually editing files on a remote server, it's a pain in the ass to xfer files after every edit to test them when I can so quickly edit them in vi.

For formatting PHP code, I installed something called php_beautifier, which will reformat PHP files according to your settings (carriage returns before braces, etc.) Saves time when you're using someone else's poorly-formatted code. (or if you prefer it a certain way.)
 
Oh my god, don't listen to that guy.

Don't use functions? hahaha what have you been smoking.

And wtf, the difference between $i++ and ++$i is negligable.

And if you want everything to be faster, just use APC or another compiler cache. It will compile the entire script and save it in memory. This is the only thing that will actually give you a 30 to 100+% performance increase GLOBALLY (not just 1 function)
 
Oh and I believe APC and other opcode caches also do their own optimizations during compilation, so for example $i++ will be changed to ++$i.. (Though it doesn't matter much..)
 
Functions & stored procedures are there so you don't have to re-enter code that you'll likely use time and time again. The performance losses are negligible (not sure if 33% is accurate), and the efficiency benefits from writing a properly designed code base WELL make up the difference.

If you're the ONLY person working on a piece of code, you might be okay doing everything in line-run code; but if you source components of your code, you'll want to "black box" as many of them as possible in to functions and SP's.
 
Oh my god, don't listen to that guy.

Don't use functions? hahaha what have you been smoking.

And wtf, the difference between $i++ and ++$i is negligable.

And if you want everything to be faster, just use APC or another compiler cache. It will compile the entire script and save it in memory. This is the only thing that will actually give you a 30 to 100+% performance increase GLOBALLY (not just 1 function)

haha gotta fucking love the hate that always comes with wesley, look dude I didn't say you shouldn't use functions read the fucking post, I said that functions can slow your code down considerably enough not to use them every two lines like most noobs seem to do.

I clearly stated that by doing this once your program hits larger sizes it'll begin to slow down considerably, I also stated if its a small program then it won't matter, fuck I even stated the obvious of use functions in moderation to the point of if your only writing 1 line then don't use them but if your going to be writing 20 or more lines over consecutively then yes use a function call.

You can honestly use all the damn compilers or scripts you want to test and fully optimize your code but if your looking to get thing up and going in a timely manner then its better not to make common mistakes pre-hand and then fix them later its better to just fix them up.

Oh and I believe APC and other opcode caches also do their own optimizations during compilation, so for example $i++ will be changed to ++$i.. (Though it doesn't matter much..)

As for the pre-increment to post-increment your right most times and in most applications this optimization technique is small enough not to be worried about but why not do it anyway and speed up your code by .5% to 1% for doing basically nothing. Again though not enough to toss a concern if you are only building small applications but as stated if you ever want to re-build on top of that application you might as well do things right the first time instead of going back and using an optimizer across your entire code and wasting hours among hours.

----------------------------------------

You know I've never really doubted your programming skills or your knowledge of it but what I do doubt about you is that you don't take enough time to read and then think for a second before you start attacking someone.

P.S. The 33% was more of a guess on my part I stated I couldn't remember what the actual number was and that one seemed to jump into my head.
 
I believe his point about the functions is if it's only a few lines, no need to put it in a function when it takes a couple of seconds to type it out where it's needed while saving you on performance.

By all means if convenience is your fortay then through one liners into functions. But if you're trying to improve performance what he suggests is another way to help.
 
Uh yea well you still said to duplicate the same function to multiple locations.. I don't know if it's going to be faster if you think about it since now PHP will have to take longer to compile the page (more code..)

Anyway.. Moving on, do talk about some more advanced optimizations..

for ($i=0; $i<count(..).. <- not good etc
regexes like you said in your last line of the orig post (ctype_digit)
require versus require_once (< php5.2)

But still, most slowdown comes from external factors, like mysql. So maybe you could show how to cache a query. Or if you have a curl app, obviously you're going to spend most your time waiting for a response from the remote server.

I still think APC is the best thing you can do and you shouldn't worry about these micro-optimizations. If your server is inadequate, move on to a better one.

(I'm not saying don't optimize, just don't over optimize to the point that it takes you longer to code or see your code clearly).

PS: apologies for my previous post, I did overreact a bit I admit :)
PS2: ++$i isn't going to bring you .5% performance increase, if you're lucky maybe 0.00001% increase.
 
Uh yea well you still said to duplicate the same function to multiple locations.. I don't know if it's going to be faster if you think about it since now PHP will have to take longer to compile the page (more code..)

Anyway.. Moving on, do talk about some more advanced optimizations..

for ($i=0; $i<count(..).. <- not good etc
regexes like you said in your last line of the orig post (ctype_digit)
require versus require_once (< php5.2)

But still, most slowdown comes from external factors, like mysql. So maybe you could show how to cache a query. Or if you have a curl app, obviously you're going to spend most your time waiting for a response from the remote server.

I still think APC is the best thing you can do and you shouldn't worry about these micro-optimizations. If your server is inadequate, move on to a better one.

(I'm not saying don't optimize, just don't over optimize to the point that it takes you longer to code or see your code clearly).

PS: apologies for my previous post, I did overreact a bit I admit :)
PS2: ++$i isn't going to bring you .5% performance increase, if you're lucky maybe 0.00001% increase.

Ahh shit its all good man I over-react in my posts as well but I consider it a way to get the creative mind working again.

Anyway that is something I agree 100% about and that damn MySql can be a killer on your application time if your doing several upon several calls to the database.

I'll write up a post about MySql cashing here a bit later on.
 
Status
Not open for further replies.