Category Archives: Uncategorized

How to Write Better PHP Code – These 7 Ways

[ad_1]

You don’t need to remember functions, classes and specific solutions to be a good programmer. They are online, accessible at any time. And being a PHP developer you are unlikely to do much important work without being connected to the internet. Then what makes a good programmer? For me a good PHP programmer means someone who is efficient – who can solve problems and build quality web based software quickly and in a way that allows easier maintenance and extending of the program.

So being a good PHP programmer means mostly to write a good code with less effort and time spent. And here is what does that mean – several main things:

– Code that is short. I don’t mean putting everything on one line like some Perl coders do, but writing less waste, reusing code and keeping it modular

– Code that is easy to maintain and extend – this again means modular, but also a well commented PHP code.

– Code that doesn’t overload the server – you shouldn’t get obsessed by this but it’s important to keep the server overload low

How to write such code? There isn’t a specific recipe – every developer has its own style regardless the fact that many use frameworks or follow specific guidelines. So I’m not going to offer you a recipe. Instead of that here are seven of the best practices I follow to write better PHP (and not only PHP) code. If you use them too, you can drastically improve your efficiency as a developer.

1. Use alternative PHP syntax in templates:

I really hope you use templates, to begin with. If you are messing the HTML output directly into your scripts, you need to work on this first. If you already follow the concept to separate your design from the program logic, you are either using some template engine (usually a dead end reducing productivity) or placing a bit of PHP code inside the templates (loops, if/else statements etc). You can add some more cleanness to your views by using the alternative PHP syntax instead of the standard one with “{” and “}”. Using foreach: / endforeach;, if: endif; for: endfor, etc. keeps the PHP code on less lines in the view, helps knowing when a loop is opened and closed and generally looks better.

You can learn more about the alternative PHP syntax on the official PHP site – just search for “Alternative syntax for control structures”.

2. Everything capsulated:

You know about the DRY, don’t you? Don’t Repeat Yourself. Don’t copy-paste code. Always use functions and classes that will encapsulate often executed tasks. I know this is ABC of programming, but are you really really doing it? If one SQL query or code block is repeating itself 3 or more times in the application, then it should be a method or function. If it is repeating itself with slight variations, it should be a method or function as well (one that takes arguments). Here is what encapsulation gives you:

– less code, less writing

– ability to make changes across the entire app with a single code change

– clean and understandable code

These three things really make a better code. Let’s get a very simple example: which you think is better – formatting the date in the SQL query or in the PHP code? Both are fine if you encapsulate the format. If you use the standard PHP date() function everywhere or the SQL date formatting function, passing the format that the client requires, to each call, what will happen if the client wants a change? You’ll have to change it everywhere. To avoid that, build your own function to format the date or just put the formatting string (the “Y/m/d H:i A” thing for example) in a constant, so you can change it any time.

3. Use a DB object:

There are many ways to handle this, including ODBC, PDO and others. Whatever you do, don’t put mysql_query() or mssql_query() (or whatever) directly in your code. It’s not that you are going to change the DB engine ten times in the project – in fact in eight years in web development I had to change the DB engine of an existing project just a couple of times. It’s again about keeping the code short, readable and better. For example I have a DB object with methods that return a single value, single array or multiple array from a DB query. This way instead of writing:

$sql=”SELECT * FROM some_table”;

$result=mysql_query($sql);

and then using $result in some construction like while($row=mysql_fetch_array($result)), I just write:

$sql=”SELECT * FROM some_table”;

$some_things=$DB->aq($sql);

And I have the result in $some_things. (Note: don’t use this when retrieving thousands of records at once, it will exhaust the server memory).

4. Use CRUD Functions:

Just in case you don’t know, CRUD comes from CReate, Update, Delete. Create functions or object methods which will do this work for you or use the well known ActiveRecord. Do this instead of writing long SQL queries with tens of fields listed. This is going to save you a lot of time. It’s going to work automatically when you add or remove a field in the HTML form. Isn’t that great?

5. Debugging is your best friend:

OK this point isn’t directly related to writing a better code – it’s more related to being a better programmer however. If something doesn’t work, you are not likely to fix it just by thinking hard or by looking at hundreds of lines of code. It’s not going to happen by swearing either. It’s going to happen by debugging.

Debugging is the action of going back following the logic of your program and finding the place where it works wrong or doesn’t work. It doesn’t matter if you use a debugger or just print_r() and echo() in various places of your code. The important thing is to trace backwards. Start from the current place – is there something wrong in it? If yes, go back few lines before the output/result happens. Is it still wrong? If yes, keep going few lines back. If no, then you know where exactly is the wrong piece of code – after this current line and before the line when your latest “is it wrong?” test returned true. I may sound bold, but I’ll say that this is the most important skill in programming (and not only) ever: to be able to go back and trace the route of the problem. If you learn to do this, you will be able to solve any solvable problem.

6. Mind the names:

A code that uses meaningful variable names is so much better – at any time you read it you know what is happening – is there a product currently modified, is it an array of users, is it the ID of the logged in, or is it anything else. I am not talking about Hungarian notation – just use variable names which correspond to the subject they represent and show whether it’s in singular or plural form. Don’t use variable names like $rows, $row, $varArr etc. Instead of that use $products when you are working with products, use $user when you are working with a single user, use $is_logged or $isLogged when you need a boolean variable showing whether the user is logged in the system. Use names that matter and be consistent in that. You’ll thank yourself later for writing such code. Other developers will thank you too.

7. Reduce DB queries:

It’s a common sense, but how many developers really do it? How many of them spend hours improving some unimportant thing like moving a sizeof() out of a loop and at the same time send a DB query in the very same loop? DB queries are the most server power consuming task in many web applications. Here are several ways to reduce the number of queries in your code:

– Use joins and left joins.

– Use inner selects when joins and left joins won’t do the job.

– Use views and temporary tables.

– Sometimes you’ll need to check something for a number of records and the previous three solutions won’t work. Instead of running a query each time, isn’t it possible to run one query for collection A, one for collection B and then use a foreach loop in PHP to check the condition? Very often it is. Be creative.

Reducing the number of queries is vital for web applications that are going to be used by many users at the same time. Sometimes you may need to sacrifice code shortness for that. This will not make your code worse – you should give the things their correct priority.

Are you following any of these guidelines in your code now?

[ad_2]

Source link

Creating a Simple User Class in PHP

[ad_1]

Most modern languages support object-oriented programming techniques, and PHP is no exception. Although many simple web development projects do not require an object-oriented approach, larger projects often do. When I’m developing a web application, and I have the choice of the programming technique to use, I normally opt for an object-oriented approach of some sort, even though I might not use all of the object-oriented capabilities made available to me by PHP.

In this article, rather than describing what objects and classes are, I’ll look at a simple example which hopefully will show how you can use an object-oriented programming technique when you are developing web applications.

Consider the following very simple HTML file.

index.htm

[html]

[head]

[/head]

[body]

[p]Welcome[/p]

[/body]

[/html]

Note: the use of square brackets instead of angle brackets is simply to ensure that the tags are not processed as HTML.

If you create and open this file in a browser it will display the word ‘Welcome’. To turn this into a piece of object-oriented software we could produce the following two files.

index.php

[?php

// Include the file containing the User class

include (‘user_class.php’);

// Create a new instance of the User class

$newUser = new User;

// Call the welcome() method

$newUser->welcome();

?]

user_class.php

[?php

class User {

// Methods

function welcome() {

print “[html]”;

print “[head]”;

print “[/head]”;

print “[body]”;

print “[p]Welcome[/p]”;

print “[/body]”;

print “[/html]”;

}

} // End of User class definition

?]

If you open index.php in a browser, it will also display the word ‘Welcome’, but this time it is done by creating a new instance of the User class ($newUser), and then calling the welcome() method, which is contained in the user_class.php file. Obviously, for a very simple web site like this, an object-oriented approach is way over the top, but you could add new methods to the user_class.php file to, for example, enable users to register and to log on, and so on. You could then call the methods you are interested in from index.php or from any other web pages that you create.

For example, if you create a method that checks whether a user is logged on, you could call that method from any page for which you wanted to provide access control. So if we wanted to add access control to index.php, we could change the files to:

index.php

[?php

// Include the file containing the User class

include (‘user_class.php’);

// Create a new instance of the User class

$newUser = new User;

// Call the checkAccess() method

$newUser->checkAccess();

// Call the welcome() method

$newUser->welcome();

?]

user_class.php

[?php

class User {

// Methods

function checkAccess() {

Code would go here to either log the user on, or to check that he/she is still logged on.

}

function welcome() {

print “[html]”;

print “[head]”;

print “[/head]”;

print “[body]”;

print “[p]Welcome[/p]”;

print “[/body]”;

print “[/html]”;

}

} // End of User class definition

?]

If the web application allows users to, for example, create documents or upload photos, you could create new classes for those requirements. This way, you can build large, complex, applications that are easily maintainable.

[ad_2]

Source link