概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:50:36 | 164 次阅读 | 评论: 0 | 来源: 网络整理

If your classes and third-party libraries follow the PSR-0 standard, you can use the ClassLoader class to load all of your project’s classes.

小技巧

You can use both the ApcClassLoader and the XcacheClassLoader to cache a ClassLoader instance or the DebugClassLoader to debug it.

Usage

Registering the ClassLoader autoloader is straightforward:

require_once '/path/to/src/Symfony/Component/ClassLoader/ClassLoader.php';

use SymfonyComponentClassLoaderClassLoader;

$loader = new ClassLoader();

// to enable searching the include path (eg. for PEAR packages)
$loader->setUseIncludePath(true);

// ... register namespaces and prefixes here - see below

$loader->register();

注解

The autoloader is automatically registered in a Symfony application (see app/autoload.php).

Use the addPrefix() or addPrefixes() methods to register your classes:

// register a single namespaces
$loader->addPrefix('Symfony', __DIR__.'/vendor/symfony/symfony/src');

// register several namespaces at once
$loader->addPrefixes(array(
    'Symfony' => __DIR__.'/../vendor/symfony/symfony/src',
    'Monolog' => __DIR__.'/../vendor/monolog/monolog/src',
));

// register a prefix for a class following the PEAR naming conventions
$loader->addPrefix('Twig_', __DIR__.'/vendor/twig/twig/lib');

$loader->addPrefixes(array(
    'Swift_' => __DIR__.'/vendor/swiftmailer/swiftmailer/lib/classes',
    'Twig_'  => __DIR__.'/vendor/twig/twig/lib',
));

Classes from a sub-namespace or a sub-hierarchy of PEAR classes can be looked for in a location list to ease the vendoring of a sub-set of classes for large projects:

$loader->addPrefixes(array(
    'DoctrineCommon'           => __DIR__.'/vendor/doctrine/common/lib',
    'DoctrineDBALMigrations' => __DIR__.'/vendor/doctrine/migrations/lib',
    'DoctrineDBAL'             => __DIR__.'/vendor/doctrine/dbal/lib',
    'Doctrine'                   => __DIR__.'/vendor/doctrine/orm/lib',
));

In this example, if you try to use a class in the DoctrineCommon namespace or one of its children, the autoloader will first look for the class under the doctrine-common directory. If not found, it will then fallback to the default Doctrine directory (the last one configured) before giving up. The order of the prefix registrations is significant in this case.

最新网友评论  共有(0)条评论 发布评论 返回顶部

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