Raises the efficiency in PHP mode through the factory pattern [reprint]
Conducting large-scale system development time, I always worry whether it should include every possible use of the class library document.
If it is included in use, the development will bring great trouble. Because I am impossible to know in advance which place will use which kind. Moreover, if each page, in accordance with the need to include or require, which is a headache, we because of will often forget that include will cause warning or fatal.
If the overall situation in a document containing all of the class library, and then all the pages contain the whole document. Thus, although simplified the work, but has actually brought the efficiency drop. Because php will contain to each document to carry on the examination. Although the PHP efficiency is very high, but examines one big pile of kind, will bring some performance the drop, specially in a large-scale system.
Has the method to be possible to satisfy both sides? Certainly there,The method is the factory pattern.
We have established the following four documents.
<?php
include_once(”f.inc.php”);
$f=new factory;
$t1=&$f->create(’T1′);
echo $t1->getName();
echo $config;
?>
f.inc.php
<?php
class factory
{
function factory()
{
$this->mClasses=array(’T1′=>’t1.inc.php’,'T2′=>’t2.inc.php’);
}
function &create($class)
{
if (!class_exists($class))
{
require_once($this->mClasses[$class]);
}
return new $class;
}
}
?>
t1.inc.php
<?php
global $config;
$config=’surfchen’;
class T1
{
var $mName=’name::T1′;
function getName()
{
return $this->mName;
}
}
?>
t2.inc.php
<?php
class T2
{
function T2()
{
echo ‘t2 is ok’;
}
}
?>
In index.php, we passed a factory to create other instance,
In the factory, the preservation of an array $this->mClasses,format for the array ( “class name” => “class file path”).
We through the factory::create() to create an instance, in create(), the first test of whether to exist, if don’t exist, based on $this-> mClasses category corresponding to the type of document contains come. Then create and return a such examples.
Thus, we need only to factory-type document contains implementation of the script (example:index.php) on it.
Everybody possibly also noted in t1.inc.php in two lines of code.
Global $config;
$Config = ’surfchen’;
Why do we need global? Because t1.inc.php is include in factory::create, in the t1 document’s variables will approve the default function to the class. Therefore,we need one of the variables (example: $config) to index.php to global access to.
Operation index.php, will be output
Name:: T1surfchen
http://www.easemarry.com/blog/
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments
No comments yet.
Leave a comment