search
HomeBackend DevelopmentPHP TutorialExperience Sharing: Tips for PHP developers to get twice the result with half the effort_PHP Tutorial

Experience Sharing: Tips for PHP developers to get twice the result with half the effort_PHP Tutorial

Jul 20, 2016 am 10:57 AM
phpGet twice the result with half the effortWhatuseshareoccurbigDeveloperSkillofexperience

What happens if you use a large mirror as a surfboard? Maybe you will conquer the waves in a shorter time, but you definitely know deep down that this is not the right choice for surfing. The same thing applies to PHP programming, although the analogy sounds 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?

In essence, if you master the way of "doing things" in the PHP language, Then you'll be comfortable using it, so it's worth investing the energy to understand these methods. 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, the more efficient code for parsing data is roughly as follows:

<ol class="dp-c"><li class="alt"><span><span>01.</span><span class="vars">$action</span><span> = isset(</span><span class="vars">$_REQUEST</span><span>[</span><span class="string">'action'</span><span>]) ? </span><span class="vars">$_REQUEST</span><span>[</span><span class="string">'action'</span><span>] : 0; </span></span></li></ol>

3. Use var_dump for PHP code debugging

If you are looking for PHP debugging technology , I must say var_dump should be what 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 and is currently the most famous PHP template in the industry One of the engines. 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.

To put it simply, 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. Program logic, which is particularly important in multi-person collaboration projects.

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 it Do 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 not defined, access is prohibited!

If you create the page correctly, then there is no reason for anyone else to access index.php or home.php. outside the index.php page. Once index.php is accessed, you can open the required page by obtaining the variables. Your index page should contain code similar to the following:

<ol class="dp-c"><li class="alt"><span><span>define(</span><span class="string">'yourPage'</span><span>,1); </span></span></li></ol>

Then, other pages should contain:

<ol class="dp-c"><li class="alt"><span><span class="keyword">if</span><span> (!defined(</span><span class="string">'yourPage'</span><span>)) </span><span class="keyword">die</span><span>(</span><span class="string">'Access Denied'</span><span>); </span></span></li></ol>

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:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">function</span><span> dbExec(</span><span class="vars">$query</span><span>)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span class="vars">$result</span><span> = </span><span class="vars">$this</span><span>->db-></span><span class="func">exec</span><span>(</span><span class="vars">$query</span><span>);  </span>
</li>
<li>
<span class="keyword">if</span><span> (PEAR::isError(</span><span class="vars">$result</span><span>))  </span>
</li>
<li class="alt">
<span>errorRedirect(</span><span class="vars">$result</span><span>->getMessage(), true);  </span>
</li>
<li>
<span class="keyword">else</span><span> </span>
</li>
<li class="alt">
<span class="keyword">return</span><span> </span><span class="vars">$result</span><span>;  </span>
</li>
<li><span>} </span></li>
</ol>

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:

<ol class="dp-c">
<li class="alt"><span><span>01.</span><span class="comment">// checks if arguments given are integer values not less than 0 - has multiple arguments </span><span> </span></span></li>
<li>
<span class="keyword">function</span><span> sanitizeInput()  </span>
</li>
<li class="alt"><span>{  </span></li>
<li>
<span class="vars">$numargs</span><span> = func_num_args();  </span>
</li>
<li class="alt">
<span class="vars">$arg_list</span><span> = func_get_args();  </span>
</li>
<li>
<span class="keyword">for</span><span> (</span><span class="vars">$i</span><span> = 0; </span><span class="vars">$i</span><span> <span class="vars">$numargs</span><span>; </span><span class="vars">$i</span><span>++) {  </span></span>
</li>
<li class="alt">
<span class="keyword">if</span><span> (!</span><span class="func">is_numeric</span><span>(</span><span class="vars">$arg_list</span><span>[</span><span class="vars">$i</span><span>]) || </span><span class="vars">$arg_list</span><span>[</span><span class="vars">$i</span><span>] </span>
</li>
<li>
<span>errorRedirect(</span><span class="string">"Unexpected variable value"</span><span>, true);  </span>
</li>
<li class="alt"><span>}  </span></li>
<li><span>} </span></li>
</ol>

8. One php file to handle the input, and one class.php file to handle the specific functions

An important way to avoid cluttering your 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, let's say you have 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 perform the real display function:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">require_once</span><span> PROJECTROOT.</span><span class="string">'libs/messages.class.php'</span><span>;  </span></span></li>
<li>
<span class="vars">$message</span><span> = </span><span class="keyword">new</span><span> Message();  </span>
</li>
<li class="alt">
<span class="keyword">switch</span><span> (</span><span class="vars">$action</span><span>)  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span class="keyword">case</span><span> </span><span class="string">'display'</span><span>:  </span>
</li>
<li>
<span class="vars">$message</span><span>->display();  </span>
</li>
<li class="alt">
<span class="keyword">break</span><span>;  </span>
</li>
<li><span>... </span></li>
</ol>

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

9、了解你的SQL语句,并总是对其审查(Sanitize)

正如我以前所提到的,任何php网站中最重要的部分有99%的可能是数据库。因此,你需要非常熟悉如何正确的使用sql。学会关联表和更多高级技术。下面我将展示一个使用MySQL的函数示例,并使用本文第7条函数进行审查。

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

首先,我们对用户输入进行检查(通过一个GET变量传递消息id),然后我们执行我们的SQL命令。注意这儿SQL的用法。你需要了解如何使用别名和关联表。

10、当你只需要一个对象时,使用单例模式

在PHP中相当常见的一种情形时,我们只需要创建一个对象一次,然后在我们的整个程序中使用它。一个很好的例子就是smarty变量,一旦被初始化后就可以在任何地方使用。这种情形的一个很好实现方案就是单例模式。示例代码如下:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> smartyObject()  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span class="keyword">if</span><span> (</span><span class="vars">$GLOBALS</span><span>[</span><span class="string">'config'</span><span>][</span><span class="string">'SmartyObj'</span><span>] == 0)  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span class="vars">$smarty</span><span> = </span><span class="keyword">new</span><span> SmartyGame();  </span>
</li>
<li>
<span class="vars">$GLOBALS</span><span>[</span><span class="string">'config'</span><span>][</span><span class="string">'SmartyObj'</span><span>] = </span><span class="vars">$smarty</span><span>;  </span>
</li>
<li class="alt"><span>}  </span></li>
<li>
<span class="keyword">else</span><span> </span>
</li>
<li class="alt">
<span class="vars">$smarty</span><span> = </span><span class="vars">$GLOBALS</span><span>[</span><span class="string">'config'</span><span>][</span><span class="string">'SmartyObj'</span><span>];  </span>
</li>
<li>
<span class="keyword">return</span><span> </span><span class="vars">$smarty</span><span>;  </span>
</li>
<li class="alt"><span>} </span></li>
</ol>

注意,我们拥有一个全局smarty变量(该示例中它在config.php中被初始化),如果它的值为0,我们将创建一个新smarty对象。否则,它意味着该对象已经被创建,我们只需要返回它。

希望本文的介绍,能够给你带来帮助。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445759.htmlTechArticle如果你使用一面大镜子作为冲浪板会发生什么?或许你会在较短的时间内征服海浪,但是你肯定从内心深处明白,这不是冲浪的正确选择。同...
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)