📜 ⬆️ ⬇️

Autoloading in Zend Framework (Autoloading classes in the Zend Framework)

Good evening dear habrasoobschestvo. I present to you my translation of an article from the Learning Zend Framework series.

I just want to make a reservation that I am not an expert in the field of English and I do not pretend to 100% correct translation, although recently I have set myself the goal of studying it as best I can, because I want to speak, read, write freely.

Therefore, if you find any inaccuracies in my translation, if I have translated or interpreted something incorrectly, contact me, I will correct my mistakes and I will be very grateful to you.
')
So the actual translation:


Introduction



Autoloading provides a mechanism that eliminates the need to manually track the dependencies between files and classes in your PHP code.

The corresponding section of the manual for PHP tells how to connect the autoload mechanism. After connecting this mechanism, the autoload function will be automatically called when you use a class or interface that is not previously defined.

Using the autoload functions you don’t need to worry about which file you are using in your project. Having good auto loaders you do not need to worry about where the file is located in which the required class is described. You simply refer to the class in your code, and the auto loader takes over
search function ads you need class.

In addition, the use of autoload can save a lot of time, since you need more
will not need to care about whether any file is already connected or not yet. You
it is not necessary to check whether the file was connected before, and whether it will turn out that the file will also be connected
once, there is no need to require require_once (); to connect files.

Zend Framework recommends using autoload classes and provides several tools for downloading.
third-party classes, as well as loading classes within your application. This guide explains how to use class autoload features with the Zend Framework, and will help you use these features most effectively.

Goals and Design


Class Naming Conventions
.

In order to understand how to use autoload in the Zned Framework, you first need to understand
relations between class names and file names in this framework.

Zend Framework uses the class name adopted in PEAR , where there is a 1: 1 ratio between class names and file names. Simply put, in ZF, the "_" in the class name is replaced with "/" , and at the end, the suffix ".php" is added to the class name. For example, the class name “Foo_Bar_Baz” indicates the real file “Foo / Bar / Baz.php” . In addition, it is supposed to search for files in the PHP variable include_path . Which allows you to connect files by looking for them in the directories that are specified in this configuration option.

Further, we recommend using a prefix for all your projects. For example all names
classes in the Zend Framework begin with the prefix "Zend_" . This avoids name conflicts.
when using different libraries. Inside the Zend Framework, we call these prefixes spaces
names ("namespaces"). Do not confuse with the namespaces of the PHP language.

Such rules and conventions are commonly used in the Zend Framework and we recommend that you develop
adhere to these rules.

Autoloader Conventions and Design


Zend Framework implements autoloading using the Zend_Loader_Autoloader class.
which is subject to the following rules and has the following conventions:

1. Ensures namespace matching. If the class prefix is ​​missing in the registered
inside the namespace application returns FALSE. With the help of such an organization you can
transfer autoload to other auto loaders.
2. Allows you to enable fallback mode. When this mode is activated, the bootloader will try
look for classes regardless of the “namespaces” defined for the loader.

3. Allows you to disable the error output in cases where the loader can not find the desired class.
By default, this option is disabled. However, if you wish, you can turn it on.

4. Allows you to create callback functions, for example, when the user does not want
use the built-in method Zend_Loader :: loadClass () . But at the same time wants to use
auto loader mechanisms Zend_Loader_Autoloader .

5. Allows you to build chains of various loaders. So you can connect
its functions for loading classes that for example do not fall under the naming convention
classes in the Zend Framework. You can use your autoloader both before and after stanadartny
Zend Framework loader.

Basic bootloader usage.



Now that we’ve figured out the basics, you can go to practice and see how to use
class Zend_Loader_Autoloader.

The easiest way to connect a file of this class. And get a copy of the bootloader. It should also be noted
that the Zend Framework loader is built on the singleton pattern. Therefore, to obtain an object
The getInstance () method is used.

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


By default, the loader will automatically connect all classes starting with prefixes.
“Zend_” or “ZendX_” , the path to which is specified in the include_path variable.

What to do if you want to force the loader to look for your classes that have the excellent prefix
from Zend_ . You must use the registerNamespace () method. The method accepts a prefix or an array of prefixes as a parameter. After the prefixes were added using this method,
the loader will automatically search for classes with a given prefix and load them.

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


In addition to this, you can turn on the fallback mode. This means that the loader will search for all classes regardless of the prefix.

  1. $ loader -> setFallbackAutoloader ( true ) ;


Attention
Do not use the fallback mode. We recommend to refuse this option in projects
Zend Framework, no matter how tempting it may seem.

Zend_Loader_Autoloader uses the Zend_Loader :: loadClass () method, which in turn
uses the include () function to include files. In the absence of a file, include ()
returns false. And PHP will return the warning "WARNING ERROR".

This can cause some problems.
1. If the display_errors option is active, an error warning will be sent to the output stream.
2. If the error_reporting mode is set to display warnings, your log will be recorded
all file connection error warnings.

Of course, you can turn off error output inside the Zend_Loader_Autoloader even if enabled
display_errors option. However, this option will allow you to silence errors only in the output stream.
Error logs will be written anyway, so we recommend that you use prefixes to your
classes and register them in the loader.

On a note:
When this manual was written, the release of PHP 5.3 was released. Starting with this version of PHP
supports namespaces. However, ZF was developed before this opportunity
appeared in PHP, and we agreed to use namespaces inside the framework
by assigning class names to prefixes. For example, the Zend_ prefix for all framework classes.
We are planning to include support for php namespaces in the bootloader starting with version 2
framework

If you want to use your functions to autoload files and classes with,
You can add them to the Zend_Loader_Autoloader loader using the pushAutoloader () and unshiftAutoloader () methods. These methods allow you to add your loader before or after calling the Zend Framework loader, and thus form a chain of different loaders.

The advantages of this approach are that:
1. Each of these methods takes a second optional parameter which is
prefix classes to load. Those. you can specify the Zend Framework loader,
that the loader connected to the chain should process only classes with a specific prefix.
2. You will not have problems with managing the load, because all chaining methods have functions
callback. which the spl_autoload_functions () mechanism is deprived of .

  1. // Append function 'my_autoloader' to the stack,
  2. // to manage classes with the prefix 'My_':
  3. $ loader -> pushAutoloader ( 'my_autoloader' , 'my_' ) ;
  4. // Prepend static method Foo_Loader :: autoload () to the stack,
  5. // to manage classes with the prefix 'Foo_':
  6. $ loader -> unshiftAutoloader ( array ( 'Foo_Loader' , 'autoload' ) , 'Foo_' ) ;


Autoload resources.



When developing real applications, sometimes there are situations when not all libraries of an application
fall under the recommendations of the names adopted in the Zend Framework. This means that the auto loader will not be able to
find the necessary files.

So, if you read the agreement section and bootloader design, then you can guess
that Zend Framework can solve this problem. To do this, there is a class Zend_Loader_Autoloader_Resource .
A resource implies a name and a path that will search for the required classes.
and files. In the simplest case, it looks like this:

  1. $ loader = new Zend_Application_Module_Autoloader ( array (
  2. 'namespace' => 'Blog' ,
  3. 'basePath' => APPLICATION_PATH . '/ modules / blog' ,
  4. ) )


First of all, you need to inform the loader about the types of resources that will be connected.
These types are key-value pairs.

For example, take the following directory tree:

  1. path / to / some / resources /
  2. | - forms /
  3. | ` - Guestbook . php // Foo_Form_Guestbook
  4. | - models /
  5. | | - DbTable /
  6. | | ` - Guestbook . php // Foo_Model_DbTable_Guestbook
  7. | | - Guestbook . php // foo_Model_Guestbook
  8. | ` - GuestbookMapper . php // Foo_Model_GuestbookMapper


First, create a resource:

  1. $ loader = new Zend_Loader_Autoloader_Resource ( array (
  2. 'basePath' => 'path / to / some / resources /' ,
  3. 'namespace' => 'Foo' ,
  4. ) )


After that it is necessary to determine the types of resources. Zend_Loader_Autoloader_Resourse :: addResourceType () Method
accepts 3 agruments. The first argument is the name of the resource. The second argument is the directory in which you need to search for this resource relative to the root directory of the resource. The third parameter is the class prefix (or namespace).
In this example, we have 3 types of resource. the first form, located in the forms directory and having the prefix "Form_". The second model, located in the models directory and having the prefix Model_ and the third dbTable located in the appropriate directories.

  1. $ loader -> addResourceType ( 'form' , 'forms' , 'Form' )
  2. -> addResourceType ( 'model' , 'models' , 'Model' )
  3. -> addResourceType ( 'dbtable' , 'models / DbTable' , 'Model_DbTable' ) ;


After the announcement, we can upload our resources using the following classes:

  1. $ form = new Foo_Form_Guestbook ( ) ;
  2. $ guestbook = new Foo_Model_Guestbook ( ) ;


Conclusion



Zend Framework encourages the use of autoloading classes (autoloading), and initializes
this mechanism in the Zend_Application class.
We hope that this guide has given you the necessary information about using the Zend_Loader_Autoloader component as well as helping you understand its benefits, such as connecting your own class autoloaders (custom autoloaders) as well as resource autoloaders.

For a detailed introduction to the components of the framework: Zend_Loader_Autoloader and Zend_Loader_Autoloader_Resource, you can read the relevant sections of the manual. Zend_Loader_Autoloader and Zend_Loader_Autoloader_Resource .

Source: https://habr.com/ru/post/119739/


All Articles