gpt4 book ai didi

php - 限制我的 spl_autoloader 只加载我的命名空间中的类?

转载 作者:行者123 更新时间:2023-12-04 17:03:51 25 4
gpt4 key购买 nike

我刚刚开始在我的应用程序中使用自动加载器延迟加载,并且遇到了命名空间问题。自动加载器正在尝试加载诸如 new DateTime() 之类的内容。和失败。有没有什么技巧可以让我的自动加载器只针对我自己的命名空间类?

这是我目前拥有的代码。我怀疑这是一团糟,但我不知道如何纠正它:

<?php namespace RSCRM;
class Autoloader {
static public function loader($className) {
$filename = dirname(__FILE__) .'/'. str_replace("\\", '/', $className) . ".php";
if (file_exists($filename)) {
include_once($filename);
if (class_exists($className)) {
return TRUE;
}
}
return FALSE;
}
}
spl_autoload_register('\RSCRM\Autoloader::loader');

如果有人可以指出一个可靠的例子,那么 RTM 很高兴。

最佳答案

我使用的实际上改编自用于对一些 AuraPHP 库进行单元测试的自动加载器:

<?php
spl_autoload_register(function ($class) {

// a partial filename
$part = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';

// directories where we can find classes
$dirs = array(
__DIR__ . DIRECTORY_SEPARATOR . 'src',
__DIR__ . DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR . 'src',
__DIR__ . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR . 'src',
);

// go through the directories to find classes
foreach ($dirs as $dir) {

$file = $dir . DIRECTORY_SEPARATOR . $part;
if (is_readable($file)) {
require $file;
return;
}
}
});

只需确保 '$dirs' 值数组指向命名空间代码的根。

您还可以查看 PSR-0 示例实现 ( http://www.php-fig.org/psr/psr-0/ )。

您可能还想查看现有的自动加载器,例如 Aura.Autoload 或 Symfony ClassLoader 组件,尽管根据您的要求,这些可能有点过分。

我希望这有帮助。

关于php - 限制我的 spl_autoloader 只加载我的命名空间中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22746175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com