文档
Welcome! 安装(Installation) 示例列表(List of examples) 依赖注入与服务定位器(Dependency Injection/Service Location) MVC 架构(The MVC Architecture) 使用控制器(Using Controllers) 使用模型(Working with Models) 模型元数据(Models Meta-Data) 事务管理(Model Transactions) Phalcon 查询语言(Phalcon Query Language (PHQL)) 缓存对象关系映射(Caching in the ORM) 对象文档映射 ODM (Object-Document Mapper) 使用视图(Using Views) 视图助手(View Helpers) 资源文件管理(Assets Management) Volt 模版引擎(Volt: Template Engine) MVC 应用(MVC Applications) 路由(Routing) 调度控制器(Dispatching Controllers) 微应用(Micro Applications) 使用命名空间(Working with Namespaces) 事件管理器(Events Manager) 请求环境 (Request Environment) 返回响应(Returning Responses) Cookie 管理(Cookies Management) 生成 URL 和 路径(Generating URLs and Paths) 闪存消息(Flashing Messages) 使用 Session 存储数据(Storing data in Session) 过滤与清理(Filtering and Sanitizing) 上下文编码(Contextual Escaping) 验证(Validation) 表单(Forms) 读取配置(Reading Configurations) 分页(Pagination) 使用缓存提高性能(Improving Performance with Cache) 安全(Security) 加密/解密( Encryption/Decryption ) 访问控制列表 ACL(Access Control Lists ACL) 多语言支持(Multi-lingual Support) 通用类加载器 ( Universal Class Loader ) 日志记录(Logging) 注释解析器(Annotations Parser) 命令行应用(Command Line Applications) 队列(Queueing) 数据库抽象层(Database Abstraction Layer) 国际化(Internationalization) 数据库迁移(Database Migrations) 调试应用程序(Debugging Applications) Phalcon 开发工具(Phalcon Developer Tools) 提高性能:下一步该做什么?(Increasing Performance: What's next?) 单元测试(Unit testing) 授权(License)
教程

发布于 2015-08-21 15:16:12 | 279 次阅读 | 评论: 0 | 来源: 网络整理

通用类加载器(Universal Class Loader)

PhalconLoader is a component that allows you to load project classes automatically, based on some predefined rules. Since this component is written in C, it provides the lowest overhead in reading and interpreting external PHP files.

The behavior of this component is based on the PHP’s capability of autoloading classes. If a class that does not exist is used in any part of the code, a special handler will try to load it. PhalconLoader serves as the special handler for this operation. By loading classes on a need to load basis, the overall performance is increased since the only file reads that occur are for the files needed. This technique is called lazy initialization.

With this component you can load files from other projects or vendors, this autoloader is PSR-0 and PSR-4 compliant.

PhalconLoader offers four options to autoload classes. You can use them one at a time or combine them.

注册命名空间(Registering Namespaces)

If you’re organizing your code using namespaces, or external libraries do so, the registerNamespaces() provides the autoloading mechanism. It takes an associative array, which keys are namespace prefixes and their values are directories where the classes are located in. The namespace separator will be replaced by the directory separator when the loader try to find the classes. Remember always to add a trailing slash at the end of the paths.

<?php

use PhalconLoader;

// Creates the autoloader
$loader = new Loader();

// Register some namespaces
$loader->registerNamespaces(
    array(
       "ExampleBase"    => "vendor/example/base/",
       "ExampleAdapter" => "vendor/example/adapter/",
       "Example"         => "vendor/example/"
    )
);

// Register autoloader
$loader->register();

// The required class will automatically include the
// file vendor/example/adapter/Some.php
$some = new ExampleAdapterSome();

注册前缀(Registering Prefixes)

This strategy is similar to the namespaces strategy. It takes an associative array, which keys are prefixes and their values are directories where the classes are located in. The namespace separator and the “_” underscore character will be replaced by the directory separator when the loader try to find the classes. Remember always to add a trailing slash at the end of the paths.

<?php

use PhalconLoader;

// Creates the autoloader
$loader = new Loader();

// Register some prefixes
$loader->registerPrefixes(
    array(
        "Example_Base"    => "vendor/example/base/",
        "Example_Adapter" => "vendor/example/adapter/",
        "Example_"        => "vendor/example/"
    )
);

// Register autoloader
$loader->register();

// The required class will automatically include the
// file vendor/example/adapter/Some.php
$some = new Example_Adapter_Some();

注册文件夹(Registering Directories)

The third option is to register directories, in which classes could be found. This option is not recommended in terms of performance, since Phalcon will need to perform a significant number of file stats on each folder, looking for the file with the same name as the class. It’s important to register the directories in relevance order. Remember always add a trailing slash at the end of the paths.

<?php

use PhalconLoader;

// Creates the autoloader
$loader = new Loader();

// Register some directories
$loader->registerDirs(
    array(
        "library/MyComponent/",
        "library/OtherComponent/Other/",
        "vendor/example/adapters/",
        "vendor/example/"
    )
);

// Register autoloader
$loader->register();

// The required class will automatically include the file from
// the first directory where it has been located
// i.e. library/OtherComponent/Other/Some.php
$some = new Some();

注册类名(Registering Classes)

The last option is to register the class name and its path. This autoloader can be very useful when the folder convention of the project does not allow for easy retrieval of the file using the path and the class name. This is the fastest method of autoloading. However the more your application grows, the more classes/files need to be added to this autoloader, which will effectively make maintenance of the class list very cumbersome and it is not recommended.

<?php

use PhalconLoader;

// Creates the autoloader
$loader = new Loader();

// Register some classes
$loader->registerClasses(
    array(
        "Some"         => "library/OtherComponent/Other/Some.php",
        "ExampleBase" => "vendor/example/adapters/Example/BaseClass.php"
    )
);

// Register autoloader
$loader->register();

// Requiring a class will automatically include the file it references
// in the associative array
// i.e. library/OtherComponent/Other/Some.php
$some = new Some();

额外的扩展名(Additional file extensions)

Some autoloading strategies such as “prefixes”, “namespaces” or “directories” automatically append the “php” extension at the end of the checked file. If you are using additional extensions you could set it with the method “setExtensions”. Files are checked in the order as it were defined:

<?php

// Creates the autoloader
$loader = new PhalconLoader();

// Set file extensions to check
$loader->setExtensions(array("php", "inc", "phb"));

修改当前策略(Modifying current strategies)

Additional auto-loading data can be added to existing values in the following way:

<?php

// Adding more directories
$loader->registerDirs(
    array(
        "../app/library/",
        "../app/plugins/"
    ),
    true
);

Passing “true” as second parameter will merge the current values with new ones in any strategy.

安全层(Security Layer)

PhalconLoader offers a security layer sanitizing by default class names avoiding possible inclusion of unauthorized files. Consider the following example:

<?php

// Basic autoloader
spl_autoload_register(function ($className) {
    if (file_exists($className . '.php')) {
        require $className . '.php';
    }
});

The above auto-loader lacks of any security check, if by mistake in a function that launch the auto-loader, a malicious prepared string is used as parameter this would allow to execute any file accessible by the application:

<?php

// This variable is not filtered and comes from an insecure source
$className = '../processes/important-process';

// Check if the class exists triggering the auto-loader
if (class_exists($className)) {
    // ...
}

If ‘../processes/important-process.php’ is a valid file, an external user could execute the file without authorization.

To avoid these or most sophisticated attacks, PhalconLoader removes any invalid character from the class name reducing the possibility of being attacked.

自动加载事件(Autoloading Events)

In the following example, the EventsManager is working with the class loader, allowing us to obtain debugging information regarding the flow of operation:

<?php

$eventsManager = new PhalconEventsManager();

$loader = new PhalconLoader();

$loader->registerNamespaces(
    array(
        'ExampleBase'    => 'vendor/example/base/',
        'ExampleAdapter' => 'vendor/example/adapter/',
        'Example'          => 'vendor/example/'
    )
);

// Listen all the loader events
$eventsManager->attach('loader', function ($event, $loader) {
    if ($event->getType() == 'beforeCheckPath') {
        echo $loader->getCheckedPath();
    }
});

$loader->setEventsManager($eventsManager);

$loader->register();

Some events when returning boolean false could stop the active operation. The following events are supported:

Event Name Triggered Can stop operation?
beforeCheckClass Triggered before starting the autoloading process Yes
pathFound Triggered when the loader locate a class No
afterCheckClass Triggered after finish the autoloading process. If this event is launched the autoloader didn’t find the class file No

注意事项(Troubleshooting)

Some things to keep in mind when using the universal autoloader:

  • Auto-loading process is case-sensitive, the class will be loaded as it is written in the code
  • Strategies based on namespaces/prefixes are faster than the directories strategy
  • If a cache bytecode like APC is installed this will used to retrieve the requested file (an implicit caching of the file is performed)
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务