recherche
Maisondéveloppement back-endtutoriel phpConstructor Prototype Pattern 原型模式(PHP示范)

Constructor Prototype Pattern 原型模式(PHP示例)

当一个类大部分都是相同的只有部分是不同的时候,如果需要大量这个类的对象,每次都重复实例化那些相同的部分是开销很大的,而如果clone之前建立对象的那些相同的部分,就可以节约开销。

针对php的一种实现方式就是__construct()和initialize函数分开分别处理这个类的初始化,construct里面放prototype也就是公共的部分,initialize里面是每个对象特殊的部分。这样我们先建立一个类不initialize,以后每次clone这个类再进行initialize就可以了。

 在zend framework官方手册里面提到了这个http://framework.zend.com/manual/2.0/en/user-guide/database-and-models.html,但是没有细讲,下面我来分析一下

一、引入

  在zf2的model里面有一个albumTable类,相当于一个操作数据库动作的助手类,里面用到了tablegateway。

  为了每次初始化albumtable都是相同的一个类,将初始化工作放到了根目录的module.php文件的getServiceConfig(),其中用到工厂模式,并且通过回调函数,当每次ServiceManager($sm)需要实例化一个对象的时候会自动调用创建一个alumTable。下面代码我们可以看出,创建一个albumTable还需要用相同的方式创建一个AlbumTableGateWay,这个类就用到了我们所要讲的原型模式。

二、代码详解

 <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getServiceConfig()    {        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">array</span><span style="color: #000000;">(            </span>'factories' => <span style="color: #0000ff;">array</span><span style="color: #000000;">(                </span>'Album\Model\AlbumTable' =>  <span style="color: #0000ff;">function</span>(<span style="color: #800080;">$sm</span><span style="color: #000000;">) {                    </span><span style="color: #800080;">$tableGateway</span> = <span style="color: #800080;">$sm</span>->get('AlbumTableGateway'<span style="color: #000000;">);                    </span><span style="color: #800080;">$table</span> = <span style="color: #0000ff;">new</span> AlbumTable(<span style="color: #800080;">$tableGateway</span><span style="color: #000000;">);                    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$table</span><span style="color: #000000;">;                }</span>,                'AlbumTableGateway' => <span style="color: #0000ff;">function</span> (<span style="color: #800080;">$sm</span><span style="color: #000000;">) {                    </span><span style="color: #800080;">$dbAdapter</span> = <span style="color: #800080;">$sm</span>->get('Zend\Db\Adapter\Adapter'<span style="color: #000000;">);                    </span><span style="color: #800080;">$resultSetPrototype</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> ResultSet();                    </span><span style="color: #800080;">$resultSetPrototype</span>->setArrayObjectPrototype(<span style="color: #0000ff;">new</span> Album());<span style="color: #008000;">//</span><span style="color: #008000;">这个就是一个不变的原型</span>                    <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">new</span> TableGateway('album', <span style="color: #800080;">$dbAdapter</span>, <span style="color: #0000ff;">null</span>, <span style="color: #800080;">$resultSetPrototype</span>);<span style="color: #008000;">//</span><span style="color: #008000;">传入到TableGateWay的构造函数中去</span>                },<span style="color: #000000;">            )</span>,<span style="color: #000000;">        );    }</span>

注意并不是TableGateWay运用了原型模式而是ResultSet这个类运用了。每当tablegateway调用select()或者insert()等方法的时候都会建立一个ResultSet用来表示结果,这些ResultSet中公共部分被clone,而独特的部分类如data就会被initialize。

三、更多代码示例

  为了更清晰得了解这个原型,我们先抛开zend这个大框架,看一个完整的代码示例。示例来自

<a href="http://ralphschindler.com/2012/03/09/php-constructor-best-practices-and-the-prototype-pattern">PHP Constructor Best Practices And The Prototype Pattern</a>

这篇文章关于prototype pattern的部分前半部分其实是混杂怎样在构造函数中运用继承来提高扩展性,两个模式看起来可能不太好理解,我们直接看最后的代码关于prototype pattern的部分。

<span style="color: #000000;">php</span><span style="color: #008000;">//</span><span style="color: #008000;">框架中很常见的adapter类,用来适配各种数据库,封装一些基本数据库连接操作。//相当于上面代码中的adapter类</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> DbAdapter {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> fetchAllFromTable(<span style="color: #800080;">$table</span><span style="color: #000000;">) {        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$arrayOfData</span><span style="color: #000000;">;    }}</span><span style="color: #008000;">//</span><span style="color: #008000;">运用prototype pattern的类,注意construct和initialize是分开的//相当于上面zend 代码里面的ResultSet类</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> RowGateway {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(DbAdapter <span style="color: #800080;">$dbAdapter</span>, <span style="color: #800080;">$tableName</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->dbAdapter = <span style="color: #800080;">$dbAdapter</span><span style="color: #000000;">;        </span><span style="color: #800080;">$this</span>->tableName = <span style="color: #800080;">$tableName</span><span style="color: #000000;">;    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> initialize(<span style="color: #800080;">$data</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->data = <span style="color: #800080;">$data</span><span style="color: #000000;">;    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * Both methods require access to the database adapter     * to fulfill their duties     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> save() {}    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> delete() {}    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> refresh() {}}</span><span style="color: #008000;">//</span><span style="color: #008000;">相当于上面代码中的TableGateway类,关于gateway可以具体去了解一下。</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> UserRepository {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(DbAdapter <span style="color: #800080;">$dbAdapter</span>, RowGateway <span style="color: #800080;">$rowGatewayPrototype</span> = <span style="color: #0000ff;">null</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->dbAdapter = <span style="color: #800080;">$dbAdapter</span><span style="color: #000000;">;        </span><span style="color: #800080;">$this</span>->rowGatewayPrototype = (<span style="color: #800080;">$rowGatewayPrototype</span>) ? <span style="color: #0000ff;">new</span> RowGateway(<span style="color: #800080;">$this</span>->dbAdapter, 'user'<span style="color: #000000;">)    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getUsers() {        </span><span style="color: #800080;">$rows</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">();        </span><span style="color: #0000ff;">foreach</span> (<span style="color: #800080;">$this</span>->dbAdapter->fetchAllFromTable('user') <span style="color: #0000ff;">as</span> <span style="color: #800080;">$rowData</span><span style="color: #000000;">) {            </span><span style="color: #800080;">$rows</span>[] = <span style="color: #800080;">$row</span> = <span style="color: #0000ff;">clone</span> <span style="color: #800080;">$this</span>-><span style="color: #000000;">rowGatewayPrototype;            </span><span style="color: #800080;">$row</span>->initialize(<span style="color: #800080;">$rowData</span><span style="color: #000000;">);        }        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$rows</span><span style="color: #000000;">;    }}</span>

这几个类其实和上面zend代码中的类是对应的

Dbadapter -- adpater

RowGateWay -- ResultSet

UserRepository - TableGateWay

具体看代码中的注释。

这里的RowGateWay可以很明显的看出在getusers中需要大量的实例化,那么原型模式就是很必要的了。

下面是运用这个类的代码

<span style="color: #0000ff;">class</span> ReadWriteRowGateway <span style="color: #0000ff;">extends</span><span style="color: #000000;"> RowGateway {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(DbAdapter <span style="color: #800080;">$readDbAdapter</span>, DbAdapter <span style="color: #800080;">$writeDbAdapter</span>, <span style="color: #800080;">$tableName</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->readDbAdapter = <span style="color: #800080;">$readDbAdapter</span><span style="color: #000000;">;        parent</span>::__construct(<span style="color: #800080;">$writeDbAdapter</span>, <span style="color: #800080;">$tableName</span><span style="color: #000000;">);    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> refresh() {        </span><span style="color: #008000;">//</span><span style="color: #008000;"> utilize $this->readDbAdapter instead of $this->dbAdapter in RowGateway base implementation</span><span style="color: #000000;">    }}</span><span style="color: #008000;">//</span><span style="color: #008000;"> usage:</span><span style="color: #800080;">$userRepository</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> UserRepository(    </span><span style="color: #800080;">$dbAdapter</span>,    <span style="color: #0000ff;">new</span> ReadWriteRowGateway(<span style="color: #800080;">$readDbAdapter</span>, <span style="color: #800080;">$writeDbAdapter</span>, 'user'<span style="color: #000000;">));</span><span style="color: #800080;">$users</span> = <span style="color: #800080;">$userRepository</span>-><span style="color: #000000;">getUsers();</span><span style="color: #800080;">$user</span> = <span style="color: #800080;">$users</span>[0]; <span style="color: #008000;">//</span><span style="color: #008000;"> instance of ReadWriteRowGateway with a specific row of data from the db</span>

 

Déclaration
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
PHP et Python: différents paradigmes expliquésPHP et Python: différents paradigmes expliquésApr 18, 2025 am 12:26 AM

PHP est principalement la programmation procédurale, mais prend également en charge la programmation orientée objet (POO); Python prend en charge une variété de paradigmes, y compris la POO, la programmation fonctionnelle et procédurale. PHP convient au développement Web, et Python convient à une variété d'applications telles que l'analyse des données et l'apprentissage automatique.

PHP et Python: une plongée profonde dans leur histoirePHP et Python: une plongée profonde dans leur histoireApr 18, 2025 am 12:25 AM

PHP est originaire en 1994 et a été développé par Rasmuslerdorf. Il a été utilisé à l'origine pour suivre les visiteurs du site Web et a progressivement évolué en un langage de script côté serveur et a été largement utilisé dans le développement Web. Python a été développé par Guidovan Rossum à la fin des années 1980 et a été publié pour la première fois en 1991. Il met l'accent sur la lisibilité et la simplicité du code, et convient à l'informatique scientifique, à l'analyse des données et à d'autres domaines.

Choisir entre PHP et Python: un guideChoisir entre PHP et Python: un guideApr 18, 2025 am 12:24 AM

PHP convient au développement Web et au prototypage rapide, et Python convient à la science des données et à l'apprentissage automatique. 1.Php est utilisé pour le développement Web dynamique, avec une syntaxe simple et adapté pour un développement rapide. 2. Python a une syntaxe concise, convient à plusieurs champs et a un écosystème de bibliothèque solide.

PHP et frameworks: moderniser la languePHP et frameworks: moderniser la langueApr 18, 2025 am 12:14 AM

PHP reste important dans le processus de modernisation car il prend en charge un grand nombre de sites Web et d'applications et d'adapter les besoins de développement via des cadres. 1.Php7 améliore les performances et introduit de nouvelles fonctionnalités. 2. Des cadres modernes tels que Laravel, Symfony et Codeigniter simplifient le développement et améliorent la qualité du code. 3. L'optimisation des performances et les meilleures pratiques améliorent encore l'efficacité de l'application.

Impact de PHP: développement Web et au-delàImpact de PHP: développement Web et au-delàApr 18, 2025 am 12:10 AM

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

Comment fonctionne la résistance au type PHP, y compris les types scalaires, les types de retour, les types d'union et les types nullables?Comment fonctionne la résistance au type PHP, y compris les types scalaires, les types de retour, les types d'union et les types nullables?Apr 17, 2025 am 12:25 AM

Le type PHP invite à améliorer la qualité et la lisibilité du code. 1) Conseils de type scalaire: Depuis PHP7.0, les types de données de base sont autorisés à être spécifiés dans les paramètres de fonction, tels que INT, Float, etc. 2) Invite de type de retour: Assurez la cohérence du type de valeur de retour de fonction. 3) Invite de type d'union: Depuis PHP8.0, plusieurs types peuvent être spécifiés dans les paramètres de fonction ou les valeurs de retour. 4) Invite de type nullable: permet d'inclure des valeurs nulles et de gérer les fonctions qui peuvent renvoyer les valeurs nulles.

Comment PHP gère le clonage des objets (mot-clé de clone) et la méthode de magie __clone?Comment PHP gère le clonage des objets (mot-clé de clone) et la méthode de magie __clone?Apr 17, 2025 am 12:24 AM

Dans PHP, utilisez le mot-clé Clone pour créer une copie de l'objet et personnalisez le comportement de clonage via la méthode de magie du clone \ _ \ _. 1. Utilisez le mot-clé Clone pour faire une copie peu profonde, en clonant les propriétés de l'objet mais pas aux propriétés de l'objet. 2. La méthode du clone \ _ \ _ peut copier profondément les objets imbriqués pour éviter les problèmes de copie superficiels. 3. Faites attention pour éviter les références circulaires et les problèmes de performance dans le clonage et optimiser les opérations de clonage pour améliorer l'efficacité.

PHP vs Python: cas d'utilisation et applicationsPHP vs Python: cas d'utilisation et applicationsApr 17, 2025 am 12:23 AM

PHP convient aux systèmes de développement Web et de gestion de contenu, et Python convient aux scripts de science des données, d'apprentissage automatique et d'automatisation. 1.Php fonctionne bien dans la création de sites Web et d'applications rapides et évolutifs et est couramment utilisé dans CMS tel que WordPress. 2. Python a permis de manière remarquable dans les domaines de la science des données et de l'apprentissage automatique, avec des bibliothèques riches telles que Numpy et Tensorflow.

See all articles

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques moisBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
1 Il y a quelques moisBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Vous avez un jeu croisé?
1 Il y a quelques moisBy尊渡假赌尊渡假赌尊渡假赌

Outils chauds

MinGW - GNU minimaliste pour Windows

MinGW - GNU minimaliste pour Windows

Ce projet est en cours de migration vers osdn.net/projects/mingw, vous pouvez continuer à nous suivre là-bas. MinGW : un port Windows natif de GNU Compiler Collection (GCC), des bibliothèques d'importation et des fichiers d'en-tête librement distribuables pour la création d'applications Windows natives ; inclut des extensions du runtime MSVC pour prendre en charge la fonctionnalité C99. Tous les logiciels MinGW peuvent fonctionner sur les plates-formes Windows 64 bits.

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

Version Mac de WebStorm

Version Mac de WebStorm

Outils de développement JavaScript utiles

Dreamweaver Mac

Dreamweaver Mac

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)