search
HomeBackend DevelopmentPHP TutorialCreate smartly structured PHP programs_PHP Tutorial

Create smartly structured PHP programs_PHP Tutorial

Jul 21, 2016 pm 04:10 PM
phpNoitFinishEstablisharticletimeofprogramstructure


I've wanted to write this article for a long time, but never had the time to finish it. I'm not here to tell you how to do it. I hope this article is just an introduction to discuss with you how to build an effective and flexible network application.

After 2-3 years of developing web applications, my development experience has become more vivid. Looking back at the code I used to write for Geocrawler, I can’t believe it is mine. Due to the GPL, the source code in PHPBuilder is also mixed.

Recently, as an experienced PHP developer, I have been helping write SourceForge, and I think this shows the scope of the final result. Good code should be divided into multiple parts, with appropriate library and function calls, a clear database structure, and each part of the site is relatively independent from other parts.

However, this is still not the best. If I could redo it, I would focus more on separating the HTML layer from the data layer, achieving this through objects and clear function libraries.

Beautiful Graphics

I know managers like to use beautiful graphs and charts to describe them, which will leave the best impression on us. Using this idea of ​​hiding behind a structure, you can separate your logic from appearance, which means that any complex program can be expressed in an "API/Data Access Layer".

Instead of putting security checks, updated sentences, etc. in the HTML layer, it is better to put them as a whole in your API layer. And this HTML layer only contains simple function calls and returned arrays, objects or other custom objects, as well as some collections of database retrieval results, etc.

If you do this, the top level will be very thin and you can easily create and maintain it.

In the following example, this HTML interface only has some direct calls to functions in the API layer, some HTML tool libraries (it can generate a pop-up box, etc.), and some calls from the database abstraction layer. Database manipulation methods (you don't need to bind to a specific database). Basics

The most basic aspects of flexible PHP program structure are the following:

Database independence
Interface independence
Portability
Object-oriented or at least should be Composed of function libraries

Are there others?
Of course there are some other things, but I think those are too big, maybe you can point them out yourself.


Let’s talk about each of them in detail.

1. Database independence

You never know where your site will run, of course when you create it, you want it to be big and have a high flow. So you don't want to tie yourself to MS Access or any other lightweight database system. Although you can't plug into various database systems immediately, you can potentially switch between them easily. You have a few different options for abstracting away your database calls. A peculiar approach in PHP is that you have to write different code for each different database system, because the access functions for each different database in PHP are different. To get around this, you can use an abstract database access layer, like PHPLib, the next version of PEAR, and the one we describe in SourceForge.

2. Interface irrelevance

Is the technology of an application more important or the site it runs on? We don't really know. I never believed this - HTML is a standard. Especially for a web application, changes to the interface mean we always have to rewrite. But if your application is large and complex, you have to establish some other interfaces for your database, as long as you don't want to copy & paste your access check and other codes everywhere in your site program. This also means that if you design your application correctly, you can easily rewrite your site to adapt to WAP by simply writing a small WAP interface and having it call your database access object. . But if you don't design your program well, changing your HTML version to WAP version is a complicated project.

I also brought this idea into SourceForge. We have a huge user base who sends/receives bugs, tasks, etc. for us. First, we pointed out that all of this would be interfaced through our web pages, and then, due to pressure from Eric Raymond and others, we decided to use XML for the external interface to the database.

Fortunately, we separated the core logic code of the program from its interface in April. I'll try to express how we do it, hopefully it will be helpful to you in your work.

The SourceForge bug tracker and other tools are split into two libraries - the HTML library and the data access library. This data access library checks the correctness of the entered values, handles security checks, and returns TRUE or FALSE on success/failure.

Due to simplification reasons, this example is not based on a complete object model, so I have to explain this base class and some of its derived classes, etc. I think this example will give you the most common idea.Examples of HTML libraries

//connect to database
require ("database.php");

//common utils like header/footer HTML
require ("html. php");

//data access library
require ("bug_data.php");

echo site_header("Page Title");

echo " Updating a bug
";

if (bug_data_update($field1,$field2,$field3)) {

echo " Update Failed! ";

} else {

echo " Updated Bug Successfully ";
//echo the global error string
echo $feedback;
}

echo site_footer();

?>


Example of Data access library

3. Portability

There is no doubt that you don’t want your code to be used only for a fixed site. We may change the color selection in the future , element names, fonts or whatever, this should set up a config file that is included by multiple pages. A better idea is that your site is modular and you don't need to copy&paste any single HTML file, which I prefer. Put these into a function and call them wherever needed

The same approach can be used for database passwords, database connection strings, etc. These can be put into an abstraction layer for database processing. >

4. Object-oriented/functional

We are not developing in COBOL, so this means that we can divide the process into multiple function calls. Each call is an automatic behavior. , sometimes just call a short section of other functions and return the result

A good example is to check whether the user is logged in on each page. You can use cookies or query the database to complete this function, but once If you want to change your validation system, you have to change every page, but you should be able to do this by changing an ordinary function in the function library. Any time you write a piece of code, if it is going to be used. More than one place, you should consider putting it in a library

What else?

Obviously there are many things I haven't talked about, tell me yours. ideas, I'll discuss them in the next article. In particular, if you wrote a large, complex application, I'd like to hear how you planned it and what you think would be different if you redo it. .

http://www.bkjia.com/PHPjc/314028.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314028.htmlTechArticleI have wanted to write this article for a long time, but I have never had time to complete it. I'm not here to tell you how to do it. I hope this article is just an introduction to discuss with you how to build...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor