search
HomeBackend DevelopmentPHP TutorialA good article on object-oriented PHP development model (abbreviated version)_PHP tutorial

I saw some people criticizing PHP, why this part is not easy to use, and that part is not easy to use. In fact, strictly speaking, no language is easy to use, and no language has strict standards. Everything has a development process. We can't wait for these standards to be perfect before using them, right? I think no matter what language you use, you have to rely on yourself when writing programs. A programmer must have a good style, ideas, etc. I've been sorting out some information recently, and I'm sending some out now. I hope everyone can give me more opinions and support.

======================== ===============
Object-oriented PHP development model (to be improved...)
================ =======================

1. Environment
Server: Linux (Apache 2.x, MySQL4.1.x, PHP4, Perl, SHELL, CVS, Sambar)
Client: Windows (Ie6, UltraEdit, other auxiliary tools)
Test machine: windows98/2K/xp/Linux (Ie5, Ie6, mozilla, firefox)

2. Three layers of web pages, programs and databases
The so-called web pages are not ordinary static web pages. The web pages here are templates made of HTML after being split
according to the specific situation of the project analysis; The database here includes database and interface programs with other parts. Usually programs and database
programs may be mixed in one file, but they should be separated as much as possible using functions. If other programs want to use data
The library can directly call these functions and cannot directly access SQL statements.

3. Project Analysis - Data Analysis
After a project has received demand analysis, the first step before actual development is data analysis. Data analysis is to
pile up all kinds of data that will be used in the project process, classify them according to their characteristics and organize them separately. Of course
there may be various kinds of data between them. relationship. Doing this step well will give the project analysis work a good start, and also provide great convenience for the following project structure analysis and data processing process analysis.

4. Project Analysis - Data Abstraction
After data analysis, we should be able to have some rough data models and some basic data small models combined
into a large model in our minds. Generally, In this case, we create a database for maintenance of some data that needs to be changed, and make some constants for the data that does not need to be changed, and abstract relevant classes for these data types, and establish relevant methods for database operations. >Relationship interface (function form, that is, method), data and data-related operations can also abstract some basic methods,
We only need to call them in programming.

5. Project Analysis - Interface Analysis
We have analyzed the data with the purpose of combining one or several products, and since we want to make a product, we need to show it to others.
So we still need to design the interface. After considering the various interfaces as comprehensively as possible, we will make the designed interface into a template, and
write the corresponding processing interface program (so, in the eyes of the program, the interface is also A kind of data), used when writing programs.

6. Project Analysis - Process Design
The website program is very simple, just follow the process to call various data we designed.

7. Case Analysis
User system, now we analyze the simplest example, a user system.
1. Data analysis, we analyze the simplest user system, so there are only two data here, that is the user name
and password. If we continue the analysis, we will also think that we should add a number (id) to each record ), now that there are three data, there is really nothing
to add.
2. Data abstraction, a data model with only three data, thinking of its possible operation methods, we make the following arrangements,
Database interface (savetodb(), getfromdb(), delete()), respectively There is also deletion of data entering and exiting the database; changing the password (password()). In addition, considering the management and viewing of the user system, there will be a collection type of data (list).
3. Interface analysis, login, verification successful, verification error, change password, change password successfully, change password error, user registration with
, registration successful, registration error; management - user list, management - user Information viewing, management - modify user
password, management - delete user.
 4. Sample code
PHP code:



Copy code

The code is as follows:



include_once "include.php";
/*
** Purpose: User system data abstraction
** Author: Yue Letter
** Time: 2005-8-30 10:05
*/
class User {
var $id = 0;
var $Name = "";
var $Password = "";

var $db = "";
var $tpl = "";

/*
** Function: constructor, specified class Database connection used
** Parameter description: $tpl, display template service handle; $userdb, database connection
** Return value: None
** Author: Yue Xinming
** Created Time: 2005-8-30 10:37
*/
function User($vtpl = "", $userdb = "") {
if ($vtpl == "") {
global $tpl; // Externally defined database connection
$this->tpl =& $tpl;
} else {
tpl = $vtpl; }  
if ($userdb == "") {
global $db; // Externally defined database connection
$this->db =& $db;
} else {
$this-> ;db = $userdb;
  }                                                       : true/false, success/failure
** Author: Yue Xinming
** Created time: 2005-8-30 10:24
*/
function savetodb() {
if ($this->Name == "") {
return false;
}
if ($this->id) {
$strSQL = sprintf("UPDATE user SET Name= '%s', Password='%s' " "
" "WHERE id='%s'", " " $this->Password,
$ this->id
                                                                                          else {
$strSQL = sprintf("INSERT user (Name, Password) "
"VALUES ('%s', '%s')",
$this->Name,
                                                                                                                                                                 , >query($strSQL)) {
return true;
} else {
            return false;                                     ; ** Return value: true/false, success/failure
** Author: Yue Xinming
** Created time: 2005-8-30 10:32
*/
function getfromdb($ id = 0) {
if ($id) {
$strSQL = sprintf("SELECT * FROM user WHERE id='%s'", $id);
} else if ($this- >id) {
$strSQL = sprintf("SELECT * FROM user WHERE id='%s'",
$this->id );
} else if ($this ->Name != "") {
$strSQL = sprintf("SELECT * FROM user WHERE Name='%s'",
$this->Name
);
} else {
return false;
}
$this->db->query($strSQL);
if ($this->db->next_record()) { $ this-& gt; id = $ this-& gt; db-& gt; f ("id");
$ this-& gt; name = $ this- & gt; db-& gt; f ("name") ;
                           $this->Password                                                                                                          else {
return false;
}
}

/*
** Function: Delete records from the database
** Parameter description: $id, record number
** Return value: true/false, success/failure
** Author: Yue Xinming
** Creation time: 2005-8-30 10:47
*/
function delete($id = 0) {
if (is_array($id)) { //Delete multiple records at the same time
foreach($id as $i) {
$strSQL = sprintf("DELETE F ROM user WHERE id='%s'", $i);
                                                                                      } else if ($ ID) { $ Strsql = Sprintf ("Delete from User where ID = '%s'", $ ID);
} else if ($ this-& gt; id) {
$ strsql = sprintf ("DELETE FROM user WHERE id='%s'", $this->id);  t; query($strSQL);
return true;
}

/*
** Function: Display the login interface
** Parameter description: $placeholder, display position
** Return value: None
** Author: Yue Xinming
** Created time: 2005-8-30 11:00
*/
function showLogin($placeholder) {
$this->tpl->addBlockfile($placeholder, " user_showLogin",
"tpl.user_showLogin.html"
"tpl.user_showLogin.html" );
$this->t pl->setCurrentBlock("user_showLogin");
$this->tpl->setVariable (array("user_Logintitle" => "User login", "strUsername" => "Username",
"strPassword" => "Password"
                             )                     🎜>        $this->tpl->parseCurrentBlock("user_showLogin");                                                                                                                          placeholder, display position
** Return value: true/false, success/failure
** Author: Yue Xinming
** Creation time: 2005-8-30 11:12
*/
function getLogin($placeholder = "") {
if (isset($_POST["login"])) {
if ($_POST["username"] == "") {
              if ($placeholder != "") {                                                                                                                                                                                                           ");
                                                                             >             $this->getfromdb();
if ($this->Password() == $_POST["password"]) {
                                                                                             placeholder != "") {
           $this->tpl->setVarable($placeholder, "Login failed!");                                                                            }  

 /*
** Function: Display registration interface
** Parameter description: $placeholder, display position
** Return value: None
** Author: Yue Xinming
** Creation time :2005-8-30 13:33
*/
function showRegister($placeholder) {
$this->tpl->addBlockfile($placeholder, "user_showRegister",
"tpl .user_showRegister.html"
                                                                                                                                   ...                                                          this->parseCurrentBlock("user_shoRegister");
}

/*
** Function: Process registration information
** Parameter description: $placeholder, display position
** Return value: true/false, registration successful/registration failed
** Author: Yue Xinming
** Created time: 2005-8-30 15:49
*/
function getRegister ($placeholder = "") {
if (isset($_POST["register")) {
if ($_POST["username"] == "") { // Username validity check, Can be changed to other checking methods
If ($placeholder != "") { // Error message
$this->tpl->setVariable($placeholder, "The username is illegal!“); ) { // Password validity check
                                             ($ Placeholder! = "") {// Error prompts
$ This-& GT; TPL-& GT; Setvariable ($ Placeholder, "Two input passwords are inconsistent!"); 
                } 
                return false; 
            } 

            $strSQL = sprintf("SELECT COUNT(*) FROM user " 
                            . "WHERE Name='%s'", 
                              $this->Name 
                             ); 
            $this->db->query($strSQL); 
            $this->db->next_record(); 
            if ($this->db->f("COUNT(*)") > 0) { 
                return false; 
            } else { 
                $strSQL = sprintf("INSERT INTO user (Name, Password) " 
                                . "VALUES('%s', '%s')", 
                                  $this->Name, 
                                  $this->Password 
                                 ); 
                $this->db->query($strSQL); 
                return true; 
            } 
        } else { 
            return false; 
        } 
    } 
}// End of class User definition

/*
** Purpose: User system data list abstraction
** Author: Yue Xinming
** Time: 2005-8-30 17:21
*/
class UserList {
var $page = 0;
var $pages = 0;
var $pagesize = 9;
var $recordsum = 0;
var $Users = array();

var $c;
var $db = "";
var $tpl = "";

/*
* * Function: constructor, initialize some variables when creating a new class
** Parameter description: no parameters
** Return value: none
** Author: Yue Xinming
** Creation time: 2005-8-30 15:49
*/
function UserList($page = 1, $pagesize = 10,
$c, $vtpl = "", $vdb = "") {
$this->page = $page;
$this->pagesize = $pagesize;
$this->condition = $condition;
if ($vdb != " ") {
$this->db = $vdb;
} else {
global $db;
$this->db = $db;
      }                                                                                      ($vtpl != "") {
$this->tpl = $vtpl;
} else {
$this->tpl = $tpl;


        $strSQL = sprintf("SELECT COUNT(*) FROM user WHERE '%s'", 
                          $this->condition 
                         ); 
        $this->db->query($strSQL); 
        $this->db->next_record(); 
        $this->recordsum = $this->db->f("COUNT(*)"); 

        $this->pages = ceil($this->recordsum / $this->pagesize); 

        $strSQL = sprintf("SELECT * FROM user WHERE '%s' LIMIT '%s', '%s'", 
                          $this->condition, 
                          $this->page * $this->pagesize, 
                          $this->pagesize + 1 
                         ); 
        $this->db->query($strSQL); 
        for ($i = 0; $this->db->next_record(); $i ++) { 
            $this->Users[$i] = new User($this->tpl, $this->db); 
            $this->Users[$i]->id       = $this->db->f("id"); 
            $this->Users[$i]->Name     = $this->db->f("Name"); 
            $this->Users[$i]->Password = $this->db->f("Password"); 
        } 
    }


/*
** Function: Display list
** Parameter description: $placeholder, display position
** Return value: None
** Author :Yue Xinming
** Creation time: 2005-8-31 9:16
*/
function showUserList($placeholder) {
$this->tpl->addBlockfile($placeholder) , "showUserList", "tpl.showUserList.html");
$this->tpl->setCurrentBlock("showUserList");
//Add the corresponding processing code here
$this ->tpl->setVariable("strTitle", "User List");
$strTitles = array("Username", "Operation");
$RecordOperations = array("Reset Password" => "operate=passwd&id=",                                                                                                                                                                               ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐'s
$this->tpl->setCurrentBlock("showRecordsTitle");
$this->tpl->setVariable("strHead", $title);
$this-> ;tpl ->parseCurrentBlock("showRecordsTitle");                                                                    foreach ($ this->Users as $user) {
$this->tpl->setCurrentBlock("showRecords");
$this->tpl->setCurrentBlock("showCell");
            $this->tpl->setVariable("strCell", $user);                                                                    this->tpl-> ;setCurrentBlock("showCell");
$this- >tpl->setVariable("strOperation", $operation); id);
$this->tpl->parseCurrentBlock("showOperations");
$this->tpl->parseCurrentBlock("showOperations");
 
                $this->tpl->parseCurrentBlock("showCell"); 
                $this->tpl->parseCurrentBlock("showRecords"); 
            } 
        } else {    // 无记录 
            $this->tpl->setCurrentBlock("showRecords"); 
            $this->tpl->setCurrentBlock("showCell"); 
            $this->tpl->setVariable("strCell", "无记录"); 
            $this->tpl->parseCurrentBlock("showCell"); 
            $this->tpl->setCurrentBlock("showCell"); 
            $this->tpl->setVariable("strCell", " "); 
            $this->tpl->parseCurrentBlock("showCell"); 
            $this->tpl->parseCurrentBlock("showRecords"); 
        } 
        $this->tpl->setCurrentBlock("showPageInfo"); 
        $this->tpl->setVariable(array("intColspan" => "2", 
                                      "intRecordSum" => $this->recordsum, 
                                      "intPage"      => $this->page, 
                                      "intPages"     => $this->pages 
                                     ) 
                               ); 
        $this->tpl->parseCurrentBlock("showPageInfo"); 
        $this->tpl->parseCurrentBlock("showUserList"); 
    } 

?>  

HTML 代码:

[Ctrl+A to select all Note: If you need to introduce external Js, you need to refresh to execute]

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317998.htmlTechArticleI saw some people criticizing PHP, why this place is not easy to use, and that place is not easy to use. In fact, strictly speaking, no language is easy to use, and no language has strict standards...
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 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

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),