


Simple Factory Pattern in Zend Framework Graphics_PHP Tutorial
I used ZF some time ago, and it didn't feel very good to treat it as a black box. I always had the urge to look at its source code, but. . . If you look at it bit by bit, the challenge is indeed a bit big. One day it occurred to me that I haven't reviewed design patterns for a long time. To sum it up, after reviewing a design pattern, look for the source code that uses this pattern in ZF. Don’t read all the source code, but read the more “advanced” parts. When it comes to patterns, I don’t know if all patterns are included in ZF. , but there should be enough patterns. I have looked at it recently, and I am saying that I can look for other open source software to find patterns. During this period of time, all kinds of written examinations have made my life a little chaotic, but no matter what, review is still necessary. Let’s talk about ZF again. One of the advantages of ZF is that each component is relatively independent, and there is not too much dependence between components. This provides convenience for users, and of course it also provides convenience for boring and lazy people like me who want to read the source code. convenient.
Let’s take a look at the simple factory today. There is no shortage of patterns in ZF, let alone factory patterns. The famous Zend_Db uses simple factories without hesitation. Then ctrl+h (under zend studio) you will find factory There are a lot of them. If I guess correctly, most of them should be simple factories. Since Zend_Db is the most commonly used, I naturally want to see its implementation. Before looking at the source code, first review how to use Zend_Db and a simple factory (this is a stack, review the simple factory first).
Review the simple factory pattern
Use a class diagram to recall the simple factory class diagram:
1. Review the use of Zend_Db
If you don’t know how to use it, it’s a bit embarrassing to look at the source code of XXX but don’t know how to use XXX, so let’s take a brief look at the use of Zend_Db. The following paragraph is in From ZF official documents (I personally don’t like ZF documents very much, they are not as easy to read as Yii)
/public/index.php
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => '127.0.0.1',
'username' => 'webuser' ,
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
Here is the database configuration also put into the code Inside, it looks the simplest (actually the others are not difficult, it’s just that the database is placed in a different location for easier management), but this is not the best way under normal circumstances, but in order to highlight the key points, the simplest one is chosen here. Way. Pay attention to the Zend_Db::factory('Pdo_Mysql'... This paragraph
generates a $db (a Zend_Db object) above. Use the above $db to query as follows:
$db->setFetchMode(Zend_Db::FETCH_OBJ);
$result = $db->fetchAssoc(
' SELECT bug_id, bug_description, bug_status FROM bugs'
);
Continuing from the official website document, this is to fetch the record mode as Object, and then fetch, everything seems natural now, but it is still Use Zend_Db as a black box.
First, look at the code summary of zend/Db.php:
< ?php
class Zend_Db
{
/**
Set some constants and default values
*/
/**
* Factory for Zend_Db_Adapter_Abstract classes.
*
* First argument may be a string containing the base of the adapter class
* name, e.g. 'Mysqli' corresponds to class Zend_Db_Adapter_Mysqli. This
* name is currently case-insensitive, but is not ideal to rely on this behavior.
* If your class is named 'My_Company_Pdo_Mysql', where 'My_Company' is the namespace
* and 'Pdo_Mysql' is the adapter name, it is best to use the name exactly as it
* is defined in the class. This will ensure proper use of the factory API.
*
* First argument may alternatively be an object of type Zend_Config.
* The adapter class base name is read from the 'adapter' property.
* The adapter config parameters are read from the 'params' property.
*
* Second argument is optional and may be an associative array of key-value
* pairs. This is used as the argument to the adapter constructor.
*
* If the first argument is of type Zend_Config, it is assumed to contain
* all parameters, and the second argument is ignored.
*
* @param mixed $adapter String name of base adapter class, or Zend_Config object.
* @param mixed $config OPTIONAL; an array or Zend_Config object with adapter parameters.
* @return Zend_Db_Adapter_Abstract
* @throws Zend_Db_Exception
*/
public static function factory ($adapter, $config = array())
{
//使用Zend_Config对象,上述方式没有使用,直接使用Array
if ($config instanceof Zend_Config) {
$config = $config->toArray();
}
/*
* Convert Zend_Config argument to plain string
* adapter name and separate config object.
*/
if ($adapter instanceof Zend_Config) {
if (isset($adapter->params)) {
$config = $adapter->params->toArray();
}
if (isset($adapter->adapter)) {
$adapter = (string) $adapter->adapter;
} else {
$adapter = null;
}
}
/*
* Verify that adapter parameters are in an array.
*/
if (! is_array($config)) {
/**
* @see Zend_Db_Exception
*/
require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception(
'Adapter parameters must be in an array or a Zend_Config object');
}
/*
* Verify that an adapter name has been specified.
*/
if (! is_string($adapter) || empty($adapter)) {
/**
* @see Zend_Db_Exception
*/
require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception(
'Adapter name must be specified in a string');
}
/*
* Form full adapter class name
*/
$adapterNamespace = 'Zend_Db_Adapter';
if (isset($config['adapterNamespace'])) {
if ($config['adapterNamespace'] != '') {
$adapterNamespace = $config['adapterNamespace'];
}
unset($config['adapterNamespace']);
}
// Adapter no longer normalized- see http://framework.zend.com/issues/browse/ZF-5606
$adapterName = $adapterNamespace . '_';
$adapterName .= str_replace(' ', '_',
ucwords(str_replace('_', ' ', strtolower($adapter))));
/*
* Load the adapter class. This throws an exception
* if the specified class cannot be loaded.
*/
if (! class_exists($adapterName)) {
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($adapterName);
}
/*
* Create an instance of the adapter class.
* Pass the config to the adapter class constructor.
*/
$dbAdapter = new $adapterName($config);
/*
* Verify that the object created is a descendent of the abstract adapter type.
*/
if (! $dbAdapter instanceof Zend_Db_Adapter_Abstract) {
/**
* @see Zend_Db_Exception
*/
require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception(
"Adapter class '$adapterName' does not extend Zend_Db_Adapter_Abstract");
}
return $dbAdapter;
}
}
最上方的注释非常值得看,它清楚的说明了这个工厂,另外一段比较重要的几段代码(忽略其中的异常处理)是:
//factory有一个参数叫做$adapter
public static function factory($adapter, $config = array())
//确定namespace
$adapterNamespace = 'Zend_Db_Adapter';
//用namespace和上面传入的$adapter构造类名
$adapterName = $adapterNamespace . '_';
$adapterName .= str_replace(' ', '_', ucwords(str_replace('_', ' ', strtolower($adapter))));
//用上面生成的类名new出obj,看起来PHP比java方便那么一点点哈(Class.forName(‘XXX').newInstance())
$dbAdapter = new $adapterName($config);
Recall the above place where Zend_Db::factory was used to generate $db:
$ db = Zend_Db::factory('Pdo_Mysql', array(
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
The first parameter of the factory method is that $adapter is Pdo_Mysql, remember here is Pdo_Mysql , jump again, according to the above $adapterNamespace = 'Zend_Db_Adapter'; you can see that the generated value of $dbAdapter must eventually be: Zend_Db_Adapter_Pdo_Mysql, ok, according to this name, find the zend/db/adapter/pdo directory, ha, so There are so many familiar faces. I saw familiar old faces such as MySql, Mssql, and Sqlite.

Note, note, there is also a low-key Abstract.php inside, which contains their parent class Zend_Db_Adapter_Pdo_Abstract. Open Mysql.php and you can see
class Zend_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Abstract
Well, the class name Zend_Db_Adapter_Pdo_Mysql is the same as the name generated above. Looking at the classes in several other files, they all inherit from Zend_Db_Adapter_Pdo_Abstract. If you want to draw a class diagram, you should have a class diagram like the following:

Then add Zend_Db, where the Client and factory functions are called, this is simple The class diagram should be,

A very, very pure simple factory comes out like this (isn’t it like a simple factory class diagram? That’s just because the position of the class is not placed good).

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

iOS devices have long been able to track your sleep patterns and more using the Health app. But isn’t it annoying when you’re disturbed by notifications while you’re sleeping? These notifications may be irrelevant and therefore disrupt your sleep patterns in the process. While Do Not Disturb mode is a great way to avoid distractions while sleeping, it can cause you to miss important calls and messages you receive during the night. Thankfully, this is where sleep mode comes in. Let’s learn more about it and how to use it on iPhone. What role does sleep mode play on the iPhone? Sleep mode is a dedicated focus mode in iOS that is automatically activated based on your sleep schedule in the "Health" App. It helps you set an alarm and then

Earphones are very common in today's life and are smart devices used by every user. Some users are curious about whether r is a left or right earphone. Let’s take a look at the meanings of headphones r and l respectively. How do you tell whether r is a left or right earphone? Answer: Right ear. 1. R on the headset is the abbreviation of right, L is the abbreviation of left; 2. Look for the letter logos of L and R on the headset, and find the letters L and R to distinguish them; 3. Some headsets will distinguish R Marked in red, the side with the microphone and buttons is generally on the right;

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

On iPhone 15 Pro and iPhone 15 Pro Max models, Apple introduced a physically programmable action button that replaces the traditional ring/silent switch above the volume buttons. The action button can be programmed to perform several different functions, but the ability to switch between silent and ring modes isn't gone. By default, a long press on the action button will silence the device and the button's tactile feedback will pulse three times. Both iPhone 15 Pro models will display a crossed-out bell symbol next to the time in the status bar to indicate that silent/silent mode is activated, and it will remain so until you long-press the Action button again to unmute the device. If you prefer to put your iPhone in silent mode

Windows in S mode is designed to provide enhanced security and performance by only allowing the installation of apps from the Microsoft Store. While this feature helps prevent malware and ensure a secure computing environment, it may limit users who want to install applications from sources other than the Microsoft Store. If you find yourself in this situation and keep asking yourself how to switch out of S mode in Windows 10/11, then you have come to the right place as we will walk you through how to switch out in Windows 10/11 using two different methods Steps to S Mode ensure you can enjoy the freedom of installing apps from anywhere you choose. Learn how to switch out of S mode in Windows

How to write a simple online reservation system through PHP. With the popularity of the Internet and users' pursuit of convenience, online reservation systems are becoming more and more popular. Whether it is a restaurant, hospital, beauty salon or other service industry, a simple online reservation system can improve efficiency and provide users with a better service experience. This article will introduce how to use PHP to write a simple online reservation system and provide specific code examples. Create database and tables First, we need to create a database to store reservation information. In MyS
