PHP语言的动态特性
http://www.ibm.com/developerworks/xml/library/os-php-flexobj/ PHP5引入的面向对象的编程特性显著的提升了PHP语言的层次。不只是成员和方法的访问控制private, protected, public -- 和Java, C++, 或C#一样 -- 你同时还能创建运行期间能动态改变的对象,
http://www.ibm.com/developerworks/xml/library/os-php-flexobj/
PHP5引入的面向对象的编程特性显著的提升了PHP语言的层次。不只是成员和方法的访问控制private, protected, public -- 和Java, C++, 或C#一样 -- 你同时还能创建运行期间能动态改变的对象,动态的创建一个新的方法和属性。这些是Java, C++, 或C#语言无法提供的。这种语言能力使得类似于ROR这样的快速开发框架变得可能。
在进入正题之前,先提个醒:这篇文章涉及PHP5里面很高级的OOP特性使用,而这些特性并非在所有的应用程序中都会使用。而且,这些特性比较难以理解,如果你对OOP没有深刻理解的话,至少你得初步了解PHP对象的语法。
动态特性的重要性The importance of being dynamic
对象是双刃剑。一方面,对象是很好的封装数据和逻辑的方法,创建系统更直观且更易于维护。另一方面,它也可能会引起类膨胀,代码变得琐碎,需要编写大量重复性的代码,你只能希望中间不犯错误。这个问题的一个典型例子就是数据库访问和操作的对象。一般而言,你需要为每一张表创建一个简单的类,提供CRUD等方法。但也有另外的方法,创建一个空对象,设置属性,然后插入数据库。
比如你有一张表Customers, 你得创建一个Customer对象,拥有表中字段所对应的属性,代表单个客户。这个Customer对象允许你insert, update或者delete相应的数据库记录。这看来不错,能工作,但有一堆代码要写。如果你有20张表,那么你需要写20个类。
有三个方法来解决这个问题。第一个方法copy/paste/modify,对于小工程,这没什么。第二个方法是使用代码生成器读取数据库方案然后自动为你生成代码,很多开发框架提供代码生成器,这是个好主意。第三个方法,也就是本文所述,是通过编写一个简单的类,在运行时根据给定表的字段动态模型化。这个类比之前的特定表格的模型类性能上要差点,但是代码精简了很多。这个方法对于设计经常变动的项目特别合算。
那么,怎么写一个柔韧的类呢?
写一个柔性类Writing a bendy class
对象拥有两个方面:成员变量和方法。对于传统的编译语言,如Java,如果你想调用一个不存在的方法或者一个不存在的成员变量,会报编译错误。对于PHP,情况如何呢?
PHP的一个方法调用,工作方式如下。首先,PHP解释器查看该类的方法,如果方法存在,那么直接调用。否则,调用该类的魔法函数__call如果该方法存在的话,如果调用失败,则调用父类的方法,以此类推。
魔法函数是特定命名的方法,这个方法由PHP解释器在脚本执行的特定节点所触发。
最常见的魔法函数是对象创建时调用的构造函数。
__call方法有两个参数:请求方法名和参数。通过__call机制实现和自己写一个方法,对函数调用者而言,效果是一样的。这样,你可以创建一个包含"无数"方法的对象。
除了__call方法, 其他魔法函数,如__get 和 __set, 是在引用不存在的实例变量的时候被调用。记住这一点,你可以开始写适用于任何数据库表访问的类了。
(以下主要是代码重构,保持原文)
传统的数据库访问方式Classic database access
Let's start with a simple database schema. The schema shown in Listing 1 is for a single data-table database that holds a list of books.
Listing 1. The MySQL database schema
DROP TABLE IF EXISTS book;
CREATE TABLE book (
book_id INT NOT NULL AUTO_INCREMENT,
title TEXT,
publisher TEXT,
author TEXT,
PRIMARY KEY( book_id )
);
Load this schema into a database named bookdb.
Next, write a conventional database class that you will then modify to become dynamic. Listing 2 shows a simple database access class for the book table.
Listing 2. The basic database access client
<?php require_once("DB.php"); $dsn = 'mysql://root:password@localhost/bookdb'; $db =& DB::Connect( $dsn, array() ); if (PEAR::isError($db)) { die($db->getMessage()); } class Book { private $book_id; private $title; private $author; private $publisher; function __construct() { } function set_title( $title ) { $this->title = $title; } function get_title( ) { return $this->title; } function set_author( $author ) { $this->author = $author; } function get_author( ) { return $this->author; } function set_publisher( $publisher ) { $this->publisher = $publisher; } function get_publisher( ) { return $this->publisher; } function load( $id ) { global $db; $res = $db->query( "SELECT * FROM book WHERE book_id=?", array( $id ) ); $res->fetchInto( $row, DB_FETCHMODE_ASSOC ); $this->book_id = $id; $this->title = $row['title']; $this->author = $row['author']; $this->publisher = $row['publisher']; } function insert() { global $db; $sth = $db->prepare( 'INSERT INTO book ( book_id, title, author, publisher ) VALUES ( 0, ?, ?, ? )' ); $db->execute( $sth, array( $this->title, $this->author, $this->publisher ) ); $res = $db->query( "SELECT last_insert_id()" ); $res->fetchInto( $row ); return $row[0]; } function update() { global $db; $sth = $db->prepare( 'UPDATE book SET title=?, author=?, publisher=? WHERE book_id=?' ); $db->execute( $sth, array( $this->title, $this->author, $this->publisher, $this->book_id ) ); } function delete() { global $db; $sth = $db->prepare( 'DELETE FROM book WHERE book_id=?' ); $db->execute( $sth, array( $this->book_id ) ); } function delete_all() { global $db; $sth = $db->prepare( 'DELETE FROM book' ); $db->execute( $sth ); } } $book = new Book(); $book->delete_all(); $book->set_title( "PHP Hacks" ); $book->set_author( "Jack Herrington" ); $book->set_publisher( "O'Reilly" ); $id = $book->insert(); echo ( "New book id = $id\n" ); $book2 = new Book(); $book2->load( $id ); echo( "Title = ".$book2->get_title()."\n" ); $book2->delete( ); ?>
To keep the code simple, I put the class and the test code in one file. The file starts with getting the database handle, which it stores in a global variable. The Book class is then defined, with private member variables for each field. A set of methods for loading, inserting, updating, and deleting rows from the database is also included.
The test code at the bottom starts by deleting all the entries from the database. Next, the code inserts a book, telling you the ID of the new record. Then, the code loads that book into another object and prints the title.
Listing 3 shows what happens when you run the code on the command line with the PHP interpreter.
Listing 3. Running the code on the command line
% php db1.php
New book id = 25
Title = PHP Hacks
%
Not much to look at, but it gets the point across. The Book object represents a row in the book data table. By using the fields and the methods above, you can create new rows, update them, and delete them.
引入一点动态A little dab of dynamic
The next step is to make the class a bit dynamic by creating the get_ and set_ methods on the fly for the individual fields. Listing 4 shows the updated code.
Listing 4. Dynamic get_ and set_ methods
<?php require_once("DB.php"); $dsn = 'mysql://root:password@localhost/bookdb'; $db =& DB::Connect( $dsn, array() ); if (PEAR::isError($db)) { die($db->getMessage()); } class Book { private $book_id; private $fields = array(); function __construct() { $this->fields[ 'title' ] = null; $this->fields[ 'author' ] = null; $this->fields[ 'publisher' ] = null; } function __call( $method, $args ) { if ( preg_match( "/set_(.*)/", $method, $found ) ) { if ( array_key_exists( $found[1], $this->fields ) ) { $this->fields[ $found[1] ] = $args[0]; return true; } } else if ( preg_match( "/get_(.*)/", $method, $found ) ) { if ( array_key_exists( $found[1], $this->fields ) ) { return $this->fields[ $found[1] ]; } } return false; } function load( $id ) { global $db; $res = $db->query( "SELECT * FROM book WHERE book_id=?", array( $id ) ); $res->fetchInto( $row, DB_FETCHMODE_ASSOC ); $this->book_id = $id; $this->set_title( $row['title'] ); $this->set_author( $row['author'] ); $this->set_publisher( $row['publisher'] ); } function insert() { global $db; $sth = $db->prepare( 'INSERT INTO book ( book_id, title, author, publisher ) VALUES ( 0, ?, ?, ? )' ); $db->execute( $sth, array( $this->get_title(), $this->get_author(), $this->get_publisher() ) ); $res = $db->query( "SELECT last_insert_id()" ); $res->fetchInto( $row ); return $row[0]; } function update() { global $db; $sth = $db->prepare( 'UPDATE book SET title=?, author=?, publisher=? WHERE book_id=?' ); $db->execute( $sth, array( $this->get_title(), $this->get_author(), $this->get_publisher(), $this->book_id ) ); } function delete() { global $db; $sth = $db->prepare( 'DELETE FROM book WHERE book_id=?' ); $db->execute( $sth, array( $this->book_id ) ); } function delete_all() { global $db; $sth = $db->prepare( 'DELETE FROM book' ); $db->execute( $sth ); } } ..
To make this change, you have to do two things. First, you must change the fields from individual instance variables to a hash table of field and value pairs. Then you must add a __call method that simply looks at the method name to see whether it was a set_ or a get_ method and set the appropriate field in the hash table.
Note that the load method actually uses the __call method by calling the set_title, set_author, and set_publisher methods -- none of which actually exists.
完全动态化Going completely dynamic
Removing the get_ and set_ methods is just a starting point. To create a completely dynamic database object, you have to give the class the name of the table and the fields, and have no hard-coded references. Listing 5 shows this change.
Listing 5. A completely dynamic database object class
<?php require_once("DB.php"); $dsn = 'mysql://root:password@localhost/bookdb'; $db =& DB::Connect( $dsn, array() ); if (PEAR::isError($db)) { die($db->getMessage()); } class DBObject { private $id = 0; private $table; private $fields = array(); function __construct( $table, $fields ) { $this->table = $table; foreach( $fields as $key ) $this->fields[ $key ] = null; } function __call( $method, $args ) { if ( preg_match( "/set_(.*)/", $method, $found ) ) { if ( array_key_exists( $found[1], $this->fields ) ) { $this->fields[ $found[1] ] = $args[0]; return true; } } else if ( preg_match( "/get_(.*)/", $method, $found ) ) { if ( array_key_exists( $found[1], $this->fields ) ) { return $this->fields[ $found[1] ]; } } return false; } function load( $id ) { global $db; $res = $db->query( "SELECT * FROM ".$this->table." WHERE ". $this->table."_id=?", array( $id ) ); $res->fetchInto( $row, DB_FETCHMODE_ASSOC ); $this->id = $id; foreach( array_keys( $row ) as $key ) $this->fields[ $key ] = $row[ $key ]; } function insert() { global $db; $fields = $this->table."_id, "; $fields .= join( ", ", array_keys( $this->fields ) ); $inspoints = array( "0" ); foreach( array_keys( $this->fields ) as $field ) $inspoints []= "?"; $inspt = join( ", ", $inspoints ); $sql = "INSERT INTO ".$this->table." ( $fields ) VALUES ( $inspt )"; $values = array(); foreach( array_keys( $this->fields ) as $field ) $values []= $this->fields[ $field ]; $sth = $db->prepare( $sql ); $db->execute( $sth, $values ); $res = $db->query( "SELECT last_insert_id()" ); $res->fetchInto( $row ); $this->id = $row[0]; return $row[0]; } function update() { global $db; $sets = array(); $values = array(); foreach( array_keys( $this->fields ) as $field ) { $sets []= $field.'=?'; $values []= $this->fields[ $field ]; } $set = join( ", ", $sets ); $values []= $this->id; $sql = 'UPDATE '.$this->table.' SET '.$set. ' WHERE '.$this->table.'_id=?'; $sth = $db->prepare( $sql ); $db->execute( $sth, $values ); } function delete() { global $db; $sth = $db->prepare( 'DELETE FROM '.$this->table.' WHERE '. $this->table.'_id=?' ); $db->execute( $sth, array( $this->id ) ); } function delete_all() { global $db; $sth = $db->prepare( 'DELETE FROM '.$this->table ); $db->execute( $sth ); } } $book = new DBObject( 'book', array( 'author', 'title', 'publisher' ) ); $book->delete_all(); $book->set_title( "PHP Hacks" ); $book->set_author( "Jack Herrington" ); $book->set_publisher( "O'Reilly" ); $id = $book->insert(); echo ( "New book id = $id\n" ); $book->set_title( "Podcasting Hacks" ); $book->update(); $book2 = new DBObject( 'book', array( 'author', 'title', 'publisher' ) ); $book2->load( $id ); echo( "Title = ".$book2->get_title()."\n" ); $book2->delete( ); ? >
Here, you change the name of the class from Book to DBObject. Then you change the constructor to take the name of the table, as well as the names of the fields in the table. After that, most of the changes happen in the methods of the class, which instead of using some hard-coded Structured Query Language (SQL) now must create the SQL strings on the fly using the table and the field names.
The only assumptions the code makes is that there is a single primary key field and that the name of that field is the name of the table plus _id. So, in the case of the book table, there is a primary key field called book_id. The primary key naming standards you use may be different; if so, you will need to change the code to suit.
This class is much more complex than the original Book class. However, from the perspective of the client of the class, this class is still simple to use. That said, I think the class could be even simpler. In particular, I don't like that I have to specify the name of the table and the fields each time I create a book. If I were to copy and paste this code all around, then change the field structure of the book table, I would be in a bad way. In Listing 6, I solved this problem by creating a simple Book class that inherits from DBObject.
Listing 6. The new Book class
.. class Book extends DBObject { function __construct() { parent::__construct( 'book', array( 'author', 'title', 'publisher' ) ); } } $book = new Book( ); $book->delete_all(); $book->{'title'} = "PHP Hacks"; $book->{'author'} = "Jack Herrington"; $book->{'publisher'} = "O'Reilly"; $id = $book->insert(); echo ( "New book id = $id\n" ); $book->{'title'} = "Podcasting Hacks"; $book->update(); $book2 = new Book( ); $book2->load( $id ); echo( "Title = ".$book2->{'title'}."\n" ); $book2->delete( ); ?>
Now, the Book class really is simple. And the client of the Book class no longer needs to know the names of the table or the fields.
还可以改进的地方Room for improvement
One final improvement I want to make on this dynamic class is to use member variables to access the fields, instead of the clunky get_ and set_ operators. Listing 7 shows how to use the __get and __set magic methods instead of __call.
Listing 7. Using the __get and __set methods
<?php require_once("DB.php"); $dsn = 'mysql://root:password@localhost/bookdb'; $db =& DB::Connect( $dsn, array() ); if (PEAR::isError($db)) { die($db->getMessage()); } class DBObject { private $id = 0; private $table; private $fields = array(); function __construct( $table, $fields ) { $this->table = $table; foreach( $fields as $key ) $this->fields[ $key ] = null; } function __get( $key ) { return $this->fields[ $key ]; } function __set( $key, $value ) { if ( array_key_exists( $key, $this->fields ) ) { $this->fields[ $key ] = $value; return true; } return false; } function load( $id ) { global $db; $res = $db->query( "SELECT * FROM ".$this->table." WHERE ". $this->table."_id=?", array( $id ) ); $res->fetchInto( $row, DB_FETCHMODE_ASSOC ); $this->id = $id; foreach( array_keys( $row ) as $key ) $this->fields[ $key ] = $row[ $key ]; } function insert() { global $db; $fields = $this->table."_id, "; $fields .= join( ", ", array_keys( $this->fields ) ); $inspoints = array( "0" ); foreach( array_keys( $this->fields ) as $field ) $inspoints []= "?"; $inspt = join( ", ", $inspoints ); $sql = "INSERT INTO ".$this->table. " ( $fields ) VALUES ( $inspt )"; $values = array(); foreach( array_keys( $this->fields ) as $field ) $values []= $this->fields[ $field ]; $sth = $db->prepare( $sql ); $db->execute( $sth, $values ); $res = $db->query( "SELECT last_insert_id()" ); $res->fetchInto( $row ); $this->id = $row[0]; return $row[0]; } function update() { global $db; $sets = array(); $values = array(); foreach( array_keys( $this->fields ) as $field ) { $sets []= $field.'=?'; $values []= $this->fields[ $field ]; } $set = join( ", ", $sets ); $values []= $this->id; $sql = 'UPDATE '.$this->table.' SET '.$set. ' WHERE '.$this->table.'_id=?'; $sth = $db->prepare( $sql ); $db->execute( $sth, $values ); } function delete() { global $db; $sth = $db->prepare( 'DELETE FROM '.$this->table.' WHERE '. $this->table.'_id=?' ); $db->execute( $sth, array( $this->id ) ); } function delete_all() { global $db; $sth = $db->prepare( 'DELETE FROM '.$this->table ); $db->execute( $sth ); } } class Book extends DBObject { function __construct() { parent::__construct( 'book', array( 'author', 'title', 'publisher' ) ); } } $book = new Book( ); $book->delete_all(); $book->{'title'} = "PHP Hacks"; $book->{'author'} = "Jack Herrington"; $book->{'publisher'} = "O'Reilly"; $id = $book->insert(); echo ( "New book id = $id\n" ); $book->{'title'} = "Podcasting Hacks"; $book->update(); $book2 = new Book( ); $book2->load( $id ); echo( "Title = ".$book2->{'title'}."\n" ); $book2->delete( ); ?>
The test code at the bottom illustrates just how much cleaner this syntax is. To get the title of the book, simply get the title member variable. That variable, in turn, calls the __get method on the object that looks for the title item in the hash table and returns it.
And there you have it: a single dynamic database access class that can bend itself to fit any table in your database.
by iefreer

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









PHP 8.4 では、いくつかの新機能、セキュリティの改善、パフォーマンスの改善が行われ、かなりの量の機能の非推奨と削除が行われています。 このガイドでは、Ubuntu、Debian、またはその派生版に PHP 8.4 をインストールする方法、または PHP 8.4 にアップグレードする方法について説明します。

あなたが経験豊富な PHP 開発者であれば、すでにそこにいて、すでにそれを行っていると感じているかもしれません。あなたは、運用を達成するために、かなりの数のアプリケーションを開発し、数百万行のコードをデバッグし、大量のスクリプトを微調整してきました。

Visual Studio Code (VS Code とも呼ばれる) は、すべての主要なオペレーティング システムで利用できる無料のソース コード エディター (統合開発環境 (IDE)) です。 多くのプログラミング言語の拡張機能の大規模なコレクションを備えた VS Code は、

JWTは、JSONに基づくオープン標準であり、主にアイデンティティ認証と情報交換のために、当事者間で情報を安全に送信するために使用されます。 1。JWTは、ヘッダー、ペイロード、署名の3つの部分で構成されています。 2。JWTの実用的な原則には、JWTの生成、JWTの検証、ペイロードの解析という3つのステップが含まれます。 3. PHPでの認証にJWTを使用する場合、JWTを生成および検証でき、ユーザーの役割と許可情報を高度な使用に含めることができます。 4.一般的なエラーには、署名検証障害、トークンの有効期限、およびペイロードが大きくなります。デバッグスキルには、デバッグツールの使用とロギングが含まれます。 5.パフォーマンスの最適化とベストプラクティスには、適切な署名アルゴリズムの使用、有効期間を合理的に設定することが含まれます。

このチュートリアルでは、PHPを使用してXMLドキュメントを効率的に処理する方法を示しています。 XML(拡張可能なマークアップ言語)は、人間の読みやすさとマシン解析の両方に合わせて設計された多用途のテキストベースのマークアップ言語です。一般的にデータストレージに使用されます

文字列は、文字、数字、シンボルを含む一連の文字です。このチュートリアルでは、さまざまな方法を使用してPHPの特定の文字列内の母音の数を計算する方法を学びます。英語の母音は、a、e、i、o、u、そしてそれらは大文字または小文字である可能性があります。 母音とは何ですか? 母音は、特定の発音を表すアルファベットのある文字です。大文字と小文字など、英語には5つの母音があります。 a、e、i、o、u 例1 入力:string = "tutorialspoint" 出力:6 説明する 文字列「TutorialSpoint」の母音は、u、o、i、a、o、iです。合計で6元があります

静的結合(静的::) PHPで後期静的結合(LSB)を実装し、クラスを定義するのではなく、静的コンテキストで呼び出しクラスを参照できるようにします。 1)解析プロセスは実行時に実行されます。2)継承関係のコールクラスを検索します。3)パフォーマンスオーバーヘッドをもたらす可能性があります。

PHPの魔法の方法は何ですか? PHPの魔法の方法には次のものが含まれます。1。\ _ \ _コンストラクト、オブジェクトの初期化に使用されます。 2。\ _ \ _リソースのクリーンアップに使用される破壊。 3。\ _ \ _呼び出し、存在しないメソッド呼び出しを処理します。 4。\ _ \ _ get、dynamic属性アクセスを実装します。 5。\ _ \ _セット、動的属性設定を実装します。これらの方法は、特定の状況で自動的に呼び出され、コードの柔軟性と効率を向上させます。
