Table of Contents
Detailed explanation of the usage of Autoloading in the Zend Framework tutorial, zendautoloading
Articles you may be interested in:
Home Backend Development PHP Tutorial Detailed explanation of Autoloading usage in Zend Framework tutorial, zendautoloading_PHP tutorial

Detailed explanation of Autoloading usage in Zend Framework tutorial, zendautoloading_PHP tutorial

Jul 12, 2016 am 08:57 AM
framework zend

Detailed explanation of the usage of Autoloading in the Zend Framework tutorial, zendautoloading

This article explains the usage of Autoloading in the Zend Framework tutorial with examples. Share it with everyone for your reference, the details are as follows:

1. Overview

Autoloading is a mechanism that eliminates the need to rely on manually writing PHP code. Refer to » PHP Manual Autoloading. Once the autoloader is defined, it will be automatically called in case you try to use an undefined class or interface.

Using automatic loading, you don’t have to worry about where classes are stored in your project. With a well-defined autoloader, you don't need to think about the location of a class file relative to the current class file, you just use the class and the autoloader will automatically find the file.

In addition, automatic loading ensures that it is loaded only once, improving performance - so it can be used instead of require_once().

Zend Framework encourages the use of autoloading and provides many tools to automatically load code libraries and application code. Here's a look at these tools and how to use them effectively.

Implementation convention of automatic loading

Class naming convention

Zend Framework borrows the idea of ​​PEAR, which is a 1:1 relationship between class names and file systems. Simply, replace the directory separator with the underscore character ("_") to represent the path to the file, and then add the suffix ".php". For example, the class "Foo_Bar_Baz" would correspond to "Foo/Bar/Baz.php" on the file system. Assuming that the location of the class has been set via PHP's include_path, this allows filenames to be found via include() and require() relative to the path set in include_path.

Also, it is recommended to use the vendor name or project name as a prefix. This means that all classes you write have a common class prefix, for example, all code in Zend Framework is prefixed with "Zend_". This naming convention helps prevent naming conflicts. In ZendFramework, we often refer to the "namespace" prefix, be careful not to confuse it with PHP's local namespace.

Autoloader design conventions

Zend Framework supports automatic loading through Zend_Loader_Autoloader, which mainly provides the following goals and design elements:

Provides namespace matching. If the namespace prefix of the class is an unregistered namespace, FALSE will be returned.

Allows defining an autoloader as an alternative autoloader. A team may be widely distributed, or use an undefined namespace prefix, in which case it will try to match any namespace prefix. However, this approach is not recommended because it may cause unnecessary lookups.
Allow to turn on the error prompt suppression. Therefore, it should be off by default. During the development phase, it can be enabled.

Automatic loading can be customized. Some developers do not want to use Zend_Loader::loadClass() for automatic loading, but still want to use Zend Framework's automatic loading mechanism. Zend_Loader_Autoloader allows the use of custom autoloading.

Allows automatic loading of callback chains using SPL. The purpose of this is to allow additional autoloaders to be specified.

2. Usage:

Usually, just introduce the need into the containing class and then instantiate it. Due to the singleton mode adopted by Zend_Loader_Autoloader, you can use the getInstance() method to obtain an instance.

require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();

Copy after login

By default, any class with a namespace prefix of "Zend_" or "ZendX_" can be loaded, just make sure the include_path is specified.
What if you want to use another namespace prefix? The best and easiest way is to call the registerNamespace() method. You can do this by passing a single namespace prefix, or an array:

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('Foo_');
$loader->registerNamespace(array('Foo_', 'Bar_'));

Copy after login

Alternatively, you can use Zend_Loader_Autoloader as a "backup" autoloader. This means that if the namespace is defined or not, autoloading will be attempted.

$loader->setFallbackAutoloader(true);

Copy after login

(Note: This method is not recommended, try not to use it).

The internal implementation of Zend_Loader_Autoloader uses Zend_Loader::loadClass() to load classes. This method uses include() to try to load the given class file. include() will return a boolean, or FALSE if not successful - and also issue a PHP warning. May cause the following problems:

If display_errors is enabled, warnings will be included in the output.

Depending on the error_reporting level you configure, it can also be output to the log.
These error messages can be suppressed as follows: (But note that when display_errors is enabled, the error log will always be displayed.)

$autoloader->suppressNotFoundWarnings(true);

Copy after login

Choose a version of Zend Framework

ZendFramework/
|-- 1.9.2/
| |-- library/
|-- ZendFramework-1.9.1-minimal/
| |-- library/
|-- 1.8.4PL1/
| |-- library/
|-- 1.8.4/
| |-- library/
|-- ZendFramework-1.8.3/
| |-- library/
|-- 1.7.8/
| |-- library/
|-- 1.7.7/
| |-- library/
|-- 1.7.6/
| |-- library/

$autoloader->setZfPath($path, 'latest');

Copy after login
$autoloader->setZfPath($path, '1.8');

Copy after login
$autoloader->setZfPath($path, '1.7.7');

Copy after login

You can also use configuration files

[production]
autoloaderZfPath = "path/to/ZendFramework"
autoloaderZfVersion = "1.7.7"
[qa]
autoloaderZfVersion = "1.8"
[development]
autoloaderZfVersion = "latest"

Copy after login

Autoloader接口

注:命名空间前缀和PHP命名空间

PHP5.3已经发布。该版本中,PHP现在已经正式支持命名空间。

然而,Zend Framework的命名空间和PHP 5.3的命名空间完全不同的。 Zend Framework中,提到的“命名空间”,是指一个类前缀。例如,所有的Zend Framework的类名称的前缀“Zend_”。 这是我们指定的“命名空间”。

在Zend Framework 2.0.0使用了原生的PHP命名空间。

自动加载器除了能够指定任意回调以外,Zend Framework还定义了一个需要自动加载类实现的接口Zend_Loader_Autoloader_Interface:

interface Zend_Loader_Autoloader_Interface
{
  public function autoload($class);
}

Copy after login

如果您希望在Zend Framework中使用自定义的自动加载器,可以使用 Zend_Loader_Autoloader的 pushAutoloader()和unshiftAutoloader()方法。
通过这些方法将在Zend Framework的内部自动装载器之后追加或之前使用自定义的加载器。

每个方法接受一个可选的第二个参数,类的命名空间前缀。自动加载器只查找给定的类前缀。如果不是指定的类前缀,将跳过自动加载器 , 这可能是一种性能改进方式。

当使用这个接口时,你需要传递类实例到Zend_Loader_Autoloader类的pushAutoloader()和unshiftAutoloader()方法,具体如下:

// Append function 'my_autoloader' to the stack,
// to manage classes with the prefix 'My_':
$loader->pushAutoloader('my_autoloader', 'My_');
// Prepend static method Foo_Loader::autoload() to the stack,
// to manage classes with the prefix 'Foo_':
$loader->unshiftAutoloader(array('Foo_Loader', 'autoload'), 'Foo_');
// Assume Foo_Autoloader implements Zend_Loader_Autoloader_Interface:
$foo = new Foo_Autoloader();
$autoloader->pushAutoloader($foo, 'Foo_');

Copy after login

Zend_Loader_Autoloader的相关方法

Method Return Value Parameters Description
getInstance() Zend_Loader_Autoloader N/A

获取实例

resetInstance() <font color="#000000" face="NSimsun">void</font> N/A

重置Zend_Loader_Autoloadersingleton实例的状态,恢复它的原始状态,注销所有的自动加载器回调和所有注册的命名空间。

autoload($class) <font color="#000000"><font face="NSimsun">string|<strong><tt>FALSE</tt></strong></font></font>
  • $class,required. A string class name to load.

试图加载一个类。

setDefaultAutoloader($callback) Zend_Loader_Autoloader
  • $callback,required.

指定默认的加载器回调

getDefaultAutoloader() <font color="#000000" face="NSimsun">callback</font> N/A

获取默认的加载器接口;默认是Zend_Loader::loadClass().

setAutoloaders(array $autoloaders) Zend_Loader_Autoloader
  • $autoloaders,required.

Set a specific autoloader list to use in the autoloader stack. Each item in the autoloader list must be a PHP callback.

getAutoloaders() Array N/A

getNamespaceAutoloaders($namespace) Array
  • $namespace,required

Get all registered autoloaders to load a specific namespace.

registerNamespace($namespace) Zend_Loader_Autoloader
  • $namespace,required.

Register a namespace. If$namespace is a string, it registers that namespace; if it's an array of strings, registers each as a namespace.

unregisterNamespace($namespace) Zend_Loader_Autoloader
  • $namespace,required.


getRegisteredNamespaces() Array N/A


suppressNotFoundWarnings($flag = null) <font color="#000000" face="NSimsun">boolean|Zend_Loader_Autoloader</font>
  • $flag,optional.

Error message

setFallbackAutoloader($flag) Zend_Loader_Autoloader
  • $flag,required.

 

isFallbackAutoloader() Boolean N/A

 

getClassAutoloaders($class) Array
  • $class,required.

 

unshiftAutoloader($callback, $namespace = '') Zend_Loader_Autoloader
  • $callback,required. A valid PHPcallback

  • $namespace,optional. A string representing a class prefix namespace.

 

pushAutoloader($callback, $namespace = '') Zend_Loader_Autoloader
  • $callback,required. A valid PHPcallback

  • $namespace,optional. A string representing a class prefix namespace.

 

removeAutoloader($callback, $namespace = '') Zend_Loader_Autoloader
  • $callback,required. A valid PHPcallback

  • $namespace,optional. A string representing a class prefix namespace, or an array of namespace strings.


Readers who are interested in more zend-related content can check out the special topics of this site: "Zend FrameWork Framework Introductory Tutorial", "php Excellent Development Framework Summary", "Yii Framework Introduction and Summary of Common Techniques", "ThinkPHP Introductory Tutorial" , "php object-oriented programming introductory tutorial", "php mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone in PHP programming.

Articles you may be interested in:

  • Zend Framework tutorial Resource Autoloading usage example
  • Zend Framework tutorial MVC framework Controller usage analysis
  • Zend Framework tutorial road by function Zend_Controller_Router detailed explanation
  • Zend Framework tutorial Zend_Controller_Plugin plug-in usage detailed explanation
  • Zend Framework tutorial response object encapsulation Zend_Controller_Response instance detailed explanation
  • Zend Framework tutorial request object Detailed explanation of the encapsulated Zend_Controller_Request instance
  • Zend Framework tutorial action base class Zend_Controller_Action detailed explanation
  • Zend Framework tutorial dispatcher Zend_Controller_Dispatcher usage detailed explanation
  • Zend Framework tutorial front-end controller Zend_Controller_Front Detailed Usage
  • Zend Framework Tutorial View Component Zend_View Usage Detailed
  • Zend Framework Tutorial Simple Example of Model Usage

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1106884.htmlTechArticleDetailed explanation of Autoloading usage in Zend Framework tutorial, zendautoloading This article explains the usage of Autoloading in Zend Framework tutorial with examples. Share it with everyone for your reference, the details are as follows: 1....
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Microsoft NET Framework Installation Issues Error Code 0x800c0006 Fix Microsoft NET Framework Installation Issues Error Code 0x800c0006 Fix May 05, 2023 pm 04:01 PM

.NET Framework 4 is required by developers and end users to run the latest versions of applications on Windows. However, while downloading and installing .NET Framework 4, many users complained that the installer stopped midway, displaying the following error message - " .NET Framework 4 has not been installed because Download failed with error code 0x800c0006 ". If you are also experiencing it while installing .NETFramework4 on your device then you are at the right place

How to identify Windows upgrade issues using SetupDiag on Windows 11/10 How to identify Windows upgrade issues using SetupDiag on Windows 11/10 Apr 17, 2023 am 10:07 AM

Whenever your Windows 11 or Windows 10 PC has an upgrade or update issue, you will usually see an error code indicating the actual reason behind the failure. However, sometimes confusion can arise when an upgrade or update fails without an error code being displayed. With handy error codes, you know exactly where the problem is so you can try to fix it. But since no error code appears, it becomes challenging to identify the issue and resolve it. This will take up a lot of your time to simply find out the reason behind the error. In this case, you can try using a dedicated tool called SetupDiag provided by Microsoft that helps you easily identify the real reason behind the error.

SCNotification has stopped working [5 steps to fix it] SCNotification has stopped working [5 steps to fix it] May 17, 2023 pm 09:35 PM

As a Windows user, you are likely to encounter SCNotification has stopped working error every time you start your computer. SCNotification.exe is a Microsoft system notification file that crashes every time you start your PC due to permission errors and network failures. This error is also known by its problematic event name. So you might not see this as SCNotification having stopped working, but as bug clr20r3. In this article, we will explore all the steps you need to take to fix SCNotification has stopped working so that it doesn’t bother you again. What is SCNotification.e

Microsoft .NET Framework 4.5.2, 4.6, and 4.6.1 will end support in April 2022 Microsoft .NET Framework 4.5.2, 4.6, and 4.6.1 will end support in April 2022 Apr 17, 2023 pm 02:25 PM

Microsoft Windows users who have installed Microsoft.NET version 4.5.2, 4.6, or 4.6.1 must install a newer version of the Microsoft Framework if they want Microsoft to support the framework through future product updates. According to Microsoft, all three frameworks will cease support on April 26, 2022. After the support date ends, the product will not receive "security fixes or technical support." Most home devices are kept up to date through Windows updates. These devices already have newer versions of frameworks installed, such as .NET Framework 4.8. Devices that are not updating automatically may

KB5012643 for Windows 11 breaks .NET Framework 3.5 apps KB5012643 for Windows 11 breaks .NET Framework 3.5 apps May 09, 2023 pm 01:07 PM

It's been a week since we talked about the new safe mode bug affecting users who installed KB5012643 for Windows 11. This pesky issue didn't appear on the list of known issues Microsoft posted on launch day, thus catching everyone by surprise. Well, just when you thought things couldn't get any worse, Microsoft drops another bomb for users who have installed this cumulative update. Windows 11 Build 22000.652 causes more problems So the tech company is warning Windows 11 users that they may experience problems launching and using some .NET Framework 3.5 applications. Sound familiar? But please don't be surprised

PHP Implementation Framework: Zend Framework Getting Started Tutorial PHP Implementation Framework: Zend Framework Getting Started Tutorial Jun 19, 2023 am 08:09 AM

PHP implementation framework: ZendFramework introductory tutorial ZendFramework is an open source website framework developed by PHP and is currently maintained by ZendTechnologies. ZendFramework adopts the MVC design pattern and provides a series of reusable code libraries to serve the implementation of Web2.0 applications and Web Serve. ZendFramework is very popular and respected by PHP developers and has a wide range of

How to use ACL (Access Control List) for permission control in Zend Framework How to use ACL (Access Control List) for permission control in Zend Framework Jul 29, 2023 am 09:24 AM

How to use ACL (AccessControlList) for permission control in Zend Framework Introduction: In a web application, permission control is a crucial function. It ensures that users can only access the pages and features they are authorized to access and prevents unauthorized access. The Zend framework provides a convenient way to implement permission control, using the ACL (AccessControlList) component. This article will introduce how to use ACL in Zend Framework

Cooler Master and Framework launch innovative mini case kit, compatible with laptop motherboards Cooler Master and Framework launch innovative mini case kit, compatible with laptop motherboards Dec 15, 2023 pm 05:35 PM

According to news on December 9, Cooler Master recently demonstrated a mini chassis kit in cooperation with notebook modular solution provider Framework at a demonstration event at the Taipei Compute Show. The unique thing about this kit is that it can be compatible with and Install the motherboard from the framework notebook. Currently, this product has begun to be sold on the market, priced at 39 US dollars, which is equivalent to approximately 279 yuan at the current exchange rate. The model number of this chassis kit is named "frameWORKMAINBOARDCASE". In terms of design, it embodies the ultimate compactness and practicality, measuring only 297x133x15 mm. Its original design is to be able to seamlessly connect to framework notebooks

See all articles