search
HomeBackend DevelopmentPHP TutorialSummary of ten tips for PHP developers to get twice the result with half the effort_PHP Tutorial

Summary of ten tips for PHP developers to get twice the result with half the effort_PHP Tutorial

Jul 21, 2016 pm 03:38 PM
phpGet twice the result with half the effortWhatusetop tenoccurbigDeveloperSkillof

What would happen if you used a large mirror as a surfboard? You may be able to conquer waves in a shorter period of time, but you surely know deep down that this is not the right choice for surfing. The same principle applies to PHP programming, although the analogy may sound a little weird. We often hear of people trying to learn PHP in just over a weekend, but IMHO this is a very poor way to learn this programming language.

Why is the process of learning PHP different from any other language?
By its nature, if you master the way of "doing things" in the PHP language, you will become more comfortable using it, so it is worth the investment to understand these ways. In PHP, simply solving problems according to your own ideas is often a wrong approach. This is not because you are a bad programmer, but because there are some standard techniques you must use if you want to write good maintainable code. Let’s take a look at the top 10 tips you need to know.

1. How to correctly create the Index page of a website
When creating every website, establishing the index page of the website is one of the first things to do. If you are new to PHP, a typical approach when writing an index page is to program only the content required for the index page, and create another page for other links. However, if you want to learn a more efficient way to implement PHP programming, you can use the "index.php?page=home" mode, which is used by many websites.

2. Use Request Global Array to capture data
In fact, we have no reason to use $_GET and $_POST arrays to capture values. The global array $_REQUEST allows you to obtain a get or form request. Therefore, in most cases a more efficient code for parsing the data would look like this:
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 0;

3. Use var_dump to debug PHP code
If you are looking for PHP debugging technology, I must say that var_dump should be the goal you are looking for. This command can meet all your needs when it comes to displaying php information. Most cases of debugging code are related to getting values ​​in PHP.

4. PHP handles the code logic and Smarty handles the presentation layer
Smarty is a template PHP template engine written in PHP. It is one of the most famous PHP template engines in the industry. . It separates logical code and external content, providing an easy-to-manage and use method to logically separate PHP code that is originally mixed with HTML code. Simply put, the purpose is to separate PHP programmers from front-end personnel, so that programmers change the logical content of the program without affecting the page design of the front-end personnel, and front-end personnel re-modify the page without affecting the program logic of the program. This is particularly important in projects involving multi-person collaboration.

5. When you really need to use global values, create a Config file
It is a bad practice to create global values ​​frequently, but sometimes the actual situation does require this. It's a good idea to use global values ​​for database table or database connection information, but don't use global values ​​frequently in your PHP code. Alternatively, a better approach is to store your global variables in a config.php file.

6. If it is not defined, access is prohibited!
If you create the page correctly, there is no reason for anyone else to access the index.php page outside of index.php or home.php. Once index.php is accessed, you can open the required page by obtaining the variables. Your index page should contain code similar to:
define('yourPage',1);
Then, other pages should contain:
if (!defined('yourPage')) die('Access Denied');
The purpose of this is to prevent direct access to your other php pages. In this way, anyone who tries to access other web pages without going through index.php will get an "Access Denied" message.

7. Create a database class
If you are doing database programming (a very common task in PHP), a good idea is to create a database class to handle any database management functions. The sample code is as follows:

Copy code The code is as follows:

public function dbExec($query)
{
$result = $this->db->exec($query);
if (PEAR::isError($result))
errorRedirect($result->getMessage(), true);
else
return $result;
}

This function only receives a query statement and executes it. It also handles any errors that may occur. You can also include audit code here, but I prefer to use a similar audit function:
Copy code Here is the code:

// checks if arguments given are integer values ​​not less than 0 - has multiple arguments
function sanitizeInput()
{
$numargs = func_num_args();
$arg_list = func_get_args();
for ($i = 0; $i if (!is_numeric($arg_list[$i]) || $arg_list[$i] errorRedirect("Unexpected variable value", true);
}
}

8. One php file processes the input, and one class.php file processes the input. Specific functions
An important way to avoid cluttering the code is to redirect it to other functions for processing after obtaining user input. The principle is very simple, the php file takes whatever input we need and then redirects its execution to a function in the class file. For example, suppose there is a URL like "index.php?page=profile&action=display". The URL is retrieved by profile.php and the action is "display". Then using a simple switch function, we execute the real display function:
Copy code The code is as follows:

require_once PROJECTROOT .'libs/messages.class.php';
$message = new Message();
switch ($action)
{
case 'display':
$message-> display();
break;
...

As shown above, I used a message class and then started doing the switch check. $message is just an object used by calling functions in the class.

9. Know your SQL statements and always Sanitize them
As I mentioned before, there are 99 most important parts of any PHP website % may be the database. Therefore, you need to be very familiar with how to use sql correctly. Learn association tables and more advanced techniques. Below I will show an example of a function using MySQL and review it using function #7 of this article.
Copy code The code is as follows:

private function getSentMessages($id)
{
$this-> ;util->sanitizeInput($id);
$pm_table = $GLOBALS['config']['privateMsg'];
$users = $GLOBALS['config']['users'];
$sql = "SELECT PM.*, USR.username as name_sender FROM $pm_table PM, $users USR
WHERE id_sender = '$id' AND sender_purge = FALSE AND USR.id = PM.id_receiver AND is_read = TRUE
ORDER BY date_sent DESC";
$result = $this->dbQueryAll($sql);
return $result;
}

First, we The user input is checked (passing the message id via a GET variable) and then we execute our SQL command. Pay attention to the usage of SQL here. You need to understand how to use aliases and related tables.

10. When you only need one object, use the singleton pattern
In a very common situation in PHP, we only need to create an object once, and then We use it throughout our program. A good example of this is smart variables, which once initialized can be used anywhere. A good implementation for this situation is the singleton pattern. The sample code is as follows:
Copy code The code is as follows:

function smartyObject()
{
if ($ GLOBALS['config']['SmartyObj'] == 0)
{
$smarty = new SmartyGame();
$GLOBALS['config']['SmartyObj'] = $smarty;
}
else
$smarty = $GLOBALS['config']['SmartyObj'];
return $smarty;
}

Note that we have A global smarty variable (in this example it is initialized in config.php), if its value is 0 we will create a new smarty object. Otherwise, it means that the object has already been created and we just need to return it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321734.htmlTechArticleWhat would happen if you used a large mirror as a surfboard? You may be able to conquer the waves in a shorter amount of time, but you surely know deep down that this is not the right choice for surfing. ...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)