Exploring PHP Best Practices

 

PHP Best Practices

ПХП Бест Працтицес

Преглед: Right from its inception, PHP is widely used to develop web based applications. Since PHP is a scripting language one must follow some rules while developing.

In this document, Ја ћу говорити о најбољим праксама које су углавном пратили у ПХП свету.

Увод: Тект не захтева никакав увод. However, као иу било које технологије, морамо следити неке смернице при изради. Ове линије водиље када се ставе заједно формирају правила добре праксе.

Следе најбоље праксе који би требало да следе радећи са ПХП:

извештавање о грешкама треба да буде укључен -

извештавање о грешкама је веома корисна функција у ПХП свету. Морамо омогућити ово док смо у фази развоја. Ово нам помаже да се идентификују проблеме у нашем коду. Најчешће се користи функција је 'Е_АЛЛ‘ што нам помаже да уочите све упозорења и критичне грешке. Мора се напоменути да је пре ставимо наш код у производњу, we should turn off this feature as this would expose all the potential errors on the browsers.

Use the DRY approach –

DRY stands for ‘Do not Repeat Yourself’. This concept is very useful programming concept and should be used in any programming language e.g. Јава, Ц #, PHP etc. Using the DRY approach we ensure that there is no redundant code. A piece of code which violates DRY is referred to as WET solution. WET stands for ‘write everything twice’ or ‘we enjoy typing’. Let us have a look into the following code –

Листинг1 – DRY & WET approach

[Code]

$mysql = mysql_connect ( ‘localhost’, ‘mysqladmin_uid’, ‘mysqladmin_pwd’ );

mysql_select_db( ‘DB_NAME’ ) or die( “Sorry !! No database selected!”);

[/Code]

This above code is based on the WET approach as the relevant parameters are hardcoded. Following the DRY approach, the above code can be changed to –

[Code]

$db_host = ‘ localhost ‘;
$db_user = ‘ mysqladmin_uid ‘;
$db_password = ‘ mysqladmin_pwd ‘;
$db_database = ‘ DB_NAME ‘;

$mysql = mysql_connect($db_host, $db_user, $db_password);
mysql_select_db($db_database);

[/Code]

Indentation and Use of whitespace –

While writing code in any programming language, we must ensure that the code is properly indented and sufficient white spaces are given wherever required. This increases the readability of the code and helps us to maintain the code in a more efficient manner.

Meaningful and consistence naming standards –

As in any programming language, PHP experts also advise to follow meaningful naming standards. We have two major approaches while we ensure to implement this –

  • Using Camel Case – In this approach, the first letter is in lower case and first letter of every word thereafter is in upper case.

Listing 2 – Code snippet using camel case

[Code]

public class MyClass {

public void methodName(Ниска argName) {

}

}

[/Code]

  • Using underscores between two words – In this approach, we put an underscore character (‘_’) between every two words. Using this approach, the above code can be modified as under –

Listing 2 – Code snippet using underscores

[Code]

public class MyClass {

public void method_име(String arg_име) {

}

}

[/Code]

Deep Nesting should be avoided –

Multilevel nesting reduces the readability of the code be it any programming language. Any programmer should avoid using deep nesting. Let’s see the following code snippet –

Listing 4 – Code snippet having multi level nesting

[Code]

public class MyClass {

public void method_name(String arg_name) {

ако (is_writable($folder)) {

ако ($fp = fopen($file_location_path,’w’)) {

ако ($stuff = extractSomeConditionalStuff()) {

ако ( fwrite ( $fp, $stuff) ) {

// …

} else {
return false;
}

} else {
return false;
}

} else {
return false;

}

} else {
return false;
}

}

}

[/Code]

The above code is a simple nested code. As we can see it is very difficult to figure which if block ends where. To have a better readability, let us modify the above code as under –

Listing 5 – Code snippet avoiding multi level nesting

[Code]

function method_name (String arg_name) {

// …

ако (!is_writable($folder)) {
return false;
}

ако (!$fp = fopen($file_location_path,’w’)) {
return false;
}

ако (!$stuff = extractSomeConditionalStuff()) {
return false;
}

ако (fwrite($fp, $stuff)) {
// …
} else {
return false;
}
}

[/Code]

Put adequate comments –

As in any programming language, make sure that your source code has enough inline comments. This is a standard practice and should be followed. This helps in further analyzing the code base as it is a standard practice that the person who is developing the code is not maintaining the same. Even if the same person is asked to make some changes in the code, inline comments will always be helpful to understand the motive of writing the code. У циљу одржавања високе класе коментар стандард у ПХП бих вам препоручио да се упознају са неким тект документације пакета нпр. пхпДоцументор.

Не стављајте пхпинфо() Функција у веб роот -

пхпинфо() је веома важна функција и треба да се користи са највећом пажњом. Помоћу ове функције било кога могу добити детаље сервера животне средине. Увек се саветује да задржи фајл који садржи пхпинфо() Функција у безбедној локацији. Када је развој врши, треба узети из кода одмах.

Никад не веруј корисника -

Ако ваша апликација обухвата било уноса корисника, напишите код на такав начин да се руковати све врсте могућих улаза. A good approach to protect our application from hackers is to always initialize your variables with some initial value that may not be relevant in the existing business flow.

Use Cache mechanism wherever required –

Good programming approaches always suggest using the cache mechanism as the cache helps us to achieve better performance. In the php world caching is achieved using –

  • Memcached – an in memory key-value pair store used for small chunks of data.
  • APC – Alternative PHP Cache an open opcode cache for PHP
  • XCache – A fast reliable PHP opcode cache
  • Zend Cache – A collection of APIs for realizing advanced caching capabilities.
  • eAcclerator – Open source caching tool

Avoid copying extra variables –

It is not a good programming practice to copy predefined variables into local variables having smaller names. This has an adverse effect on the performance of the application. Let us see the following code snippet –

Listing 6 – Copying extra variables –

[Code]

$desc = strip_tags($_POST[‘PHP description’]);

echo $desc;

[/Code]

The above code snippet is an example of copying a variable into a local variable unnecessarily. This is not at all a good practice. The same motive can be achieved by using the following code –

[Code]

echo strip_tags($_POST[‘PHP description’]);

[/Code]

Use frameworks –

Frameworks are developed after lot of research works and hence they prove to be less problematic. They make our life easier as they provide proven solutions. In PHP there are lots of frameworks available. While development, we should make use of these. One of these frameworks which are widely used is MVC or Model View Controller.

Закључак:

Let us conclude our discussion in the form of following bullets –

  • Best practices guide us to develop code in a more efficient manner.
  • Following best practices ensures better performance of the application.
  • As in other programming language, PHP also follows the best practices in the industry which ensures that the application developed is a good one.

 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share