搜尋
首頁後端開發php教程PHP管理依赖(dependency)关系工具 Composer的自动加载(autoload),dependencyautoload_PHP教程

PHP管理依赖(dependency)关系工具 Composer的自动加载(autoload),dependencyautoload

举例来说,假设我们的项目想要使用 monolog 这个日志工具,就需要在composer.json里告诉composer我们需要它:

{
 "require": {
  "monolog/monolog": "1.*"
 }
}

之后执行:

php composer.phar install

好,现在安装完了,该怎么使用呢?Composer自动生成了一个autoload文件,你只需要引用它

require '/path/to/vendor/autoload.php';

然后就可以非常方便的去使用第三方的类库了,是不是感觉很棒啊!对于我们需要的monolog,就可以这样用了:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('/path/to/log/log_name.log', Logger::WARNING));
// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');

在这个过程中,Composer做了什么呢?它生成了一个autoloader,再根据各个包自己的autoload配置,从而帮我们进行自动加载的工作。(如果对autoload这部分内容不太了解,可以看我之前的 一篇文章
)接下来让我们看看Composer是怎么做的吧。

对于第三方包的自动加载,Composer提供了四种方式的支持,分别是 PSR-0和PSR-4的自动加载(我的一篇文章也有介绍过它们),生成class-map,和直接包含files的方式。

PSR-4是composer推荐使用的一种方式,因为它更易使用并能带来更简洁的目录结构。在composer.json里是这样进行配置的:

{
  "autoload": {
    "psr-4": {
      "Foo\\": "src/",
    }
  }
}

key和value就定义出了namespace以及到相应path的映射。按照PSR-4的规则,当试图自动加载 "Foo\\Bar\\Baz" 这个class时,会去寻找 "src/Bar/Baz.php" 这个文件,如果它存在则进行加载。注意, "Foo\\"
并没有出现在文件路径中,这是与PSR-0不同的一点,如果PSR-0有此配置,那么会去寻找

"src/Foo/Bar/Baz.php"

这个文件。

另外注意PSR-4和PSR-0的配置里,"Foo\\"结尾的命名空间分隔符必须加上并且进行转义,以防出现"Foo"匹配到了"FooBar"这样的意外发生。

在composer安装或更新完之后,psr-4的配置换被转换成namespace为key,dir path为value的Map的形式,并写入生成的 vendor/composer/autoload_psr4.php 文件之中。

{
  "autoload": {
    "psr-0": {
      "Foo\\": "src/",
    }
  }
}

最终这个配置也以Map的形式写入生成的

vendor/composer/autoload_namespaces.php

文件之中。

Class-map方式,则是通过配置指定的目录或文件,然后在Composer安装或更新时,它会扫描指定目录下以.php或.inc结尾的文件中的class,生成class到指定file path的映射,并加入新生成的 vendor/composer/autoload_classmap.php 文件中,。

{
  "autoload": {
    "classmap": ["src/", "lib/", "Something.php"]
  }
}

例如src/下有一个BaseController类,那么在autoload_classmap.php文件中,就会生成这样的配置:

'BaseController' => $baseDir . '/src/BaseController.php'

Files方式,就是手动指定供直接加载的文件。比如说我们有一系列全局的helper functions,可以放到一个helper文件里然后直接进行加载

{
  "autoload": {
    "files": ["src/MyLibrary/functions.php"]
  }
}

它会生成一个array,包含这些配置中指定的files,再写入新生成的

vendor/composer/autoload_files.php

文件中,以供autoloader直接进行加载。

下面来看看composer autoload的代码吧

<&#63;php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit73612b48e6c3d0de8d56e03dece61d11
{
  private static $loader;
  public static function loadClassLoader($class)
  {
 if ('Composer\Autoload\ClassLoader' === $class) {
   require __DIR__ . '/ClassLoader.php';
 }
  }
  public static function getLoader()
  {
 if (null !== self::$loader) {
   return self::$loader;
 }
 spl_autoload_register(array('ComposerAutoloaderInit73612b48e6c3d0de8d56e03dece61d11', 'loadClassLoader'), true, true);
 self::$loader = $loader = new \Composer\Autoload\ClassLoader();
 spl_autoload_unregister(array('ComposerAutoloaderInit73612b48e6c3d0de8d56e03dece61d11', 'loadClassLoader'));
 $vendorDir = dirname(__DIR__); //verdor第三方类库提供者目录
 $baseDir = dirname($vendorDir); //整个应用的目录
 $includePaths = require __DIR__ . '/include_paths.php';
 array_push($includePaths, get_include_path());
 set_include_path(join(PATH_SEPARATOR, $includePaths));
 $map = require __DIR__ . '/autoload_namespaces.php';
 foreach ($map as $namespace => $path) {
   $loader->set($namespace, $path);
 }
 $map = require __DIR__ . '/autoload_psr4.php';
 foreach ($map as $namespace => $path) {
   $loader->setPsr4($namespace, $path);
 }
 $classMap = require __DIR__ . '/autoload_classmap.php';
 if ($classMap) {
   $loader->addClassMap($classMap);
 }
 $loader->register(true);
 $includeFiles = require __DIR__ . '/autoload_files.php';
 foreach ($includeFiles as $file) {
   composerRequire73612b48e6c3d0de8d56e03dece61d11($file);
 }
 return $loader;
  }
}
function composerRequire73612b48e6c3d0de8d56e03dece61d11($file)
{
  require $file;
}

首先初始化ClassLoader类,然后依次用上面提到的4种加载方式来注册/直接加载,ClassLoader的一些核心代码如下:

/**
  * @param array $classMap Class to filename map
  */
 public function addClassMap(array $classMap)
 {
  if ($this->classMap) {
   $this->classMap = array_merge($this->classMap, $classMap);
  } else {
   $this->classMap = $classMap;
  }
 }
 /**
  * Registers a set of PSR-0 directories for a given prefix,
  * replacing any others previously set for this prefix.
  *
  * @param string  $prefix The prefix
  * @param array|string $paths The PSR-0 base directories
  */
 public function set($prefix, $paths)
 {
  if (!$prefix) {
   $this->fallbackDirsPsr0 = (array) $paths;
  } else {
   $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
  }
 }
 /**
  * Registers a set of PSR-4 directories for a given namespace,
  * replacing any others previously set for this namespace.
  *
  * @param string  $prefix The prefix/namespace, with trailing '\\'
  * @param array|string $paths The PSR-4 base directories
  *
  * @throws \InvalidArgumentException
  */
 public function setPsr4($prefix, $paths)
 {
  if (!$prefix) {
   $this->fallbackDirsPsr4 = (array) $paths;
  } else {
   $length = strlen($prefix);
   if ('\\' !== $prefix[$length - 1]) {
    throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
   }
   $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
   $this->prefixDirsPsr4[$prefix] = (array) $paths;
  }
 }
 /**
  * Registers this instance as an autoloader.
  *
  * @param bool $prepend Whether to prepend the autoloader or not
  */
 public function register($prepend = false)
 {
  spl_autoload_register(array($this, 'loadClass'), true, $prepend);
 }
 /**
  * Loads the given class or interface.
  *
  * @param string $class The name of the class
  * @return bool|null True if loaded, null otherwise
  */
 public function loadClass($class)
 {
  if ($file = $this->findFile($class)) {
   includeFile($file);
   return true;
  }
 }
 /**
  * Finds the path to the file where the class is defined.
  *
  * @param string $class The name of the class
  *
  * @return string|false The path if found, false otherwise
  */
 public function findFile($class)
 {
  //这是PHP5.3.0 - 5.3.2的一个bug 详见https://bugs.php.net/50731
  if ('\\' == $class[0]) {
   $class = substr($class, 1);
  }
  // class map 方式的查找
  if (isset($this->classMap[$class])) {
   return $this->classMap[$class];
  }
  //psr-0/4方式的查找
  $file = $this->findFileWithExtension($class, '.php');
  // Search for Hack files if we are running on HHVM
  if ($file === null && defined('HHVM_VERSION')) {
   $file = $this->findFileWithExtension($class, '.hh');
  }
  if ($file === null) {
   // Remember that this class does not exist.
   return $this->classMap[$class] = false;
  }
  return $file;
 }
 private function findFileWithExtension($class, $ext)
 {
  // PSR-4 lookup
  $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
  $first = $class[0];
  if (isset($this->prefixLengthsPsr4[$first])) {
   foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) {
    if (0 === strpos($class, $prefix)) {
     foreach ($this->prefixDirsPsr4[$prefix] as $dir) {
      if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
       return $file;
      }
     }
    }
   }
  }
  // PSR-4 fallback dirs
  foreach ($this->fallbackDirsPsr4 as $dir) {
   if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
    return $file;
   }
  }
  // PSR-0 lookup
  if (false !== $pos = strrpos($class, '\\')) {
   // namespaced class name
   $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
    . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
  } else {
   // PEAR-like class name
   $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
  }
  if (isset($this->prefixesPsr0[$first])) {
   foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
    if (0 === strpos($class, $prefix)) {
     foreach ($dirs as $dir) {
      if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
       return $file;
      }
     }
    }
   }
  }
  // PSR-0 fallback dirs
  foreach ($this->fallbackDirsPsr0 as $dir) {
   if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
    return $file;
   }
  }
  // PSR-0 include paths.
  if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
   return $file;
  }
 }

/**
 * Scope isolated include.
 *
 * Prevents access to $this/self from included files.
 */
function includeFile($file)
{
 include $file;
}

php 为何自动加载可以等同于上面的一群require?

凉良说得对。用autoload
用法相当简单,唯一的条件你的class名字必须跟目录名对称。
可以看例子
如果log.php在class的目录里面,里面的class名就应该这样取: class_log
class class_log { }
?>

之后呢就在要include的地方加上这个function
可以看例子

function __autoload($class) {
$path_array = explode('_', $class); ///把class和log分开成array

$path = implode(DIRECTORY_SEPARATOR, $path_array); /// 把array用/重新连在一起

include $path.'.php'; 最后直接include就行了。

}

$log = new class_log();
?>

根据这个方法应该行得通。
 

PHP 自动加载对象 __autoload

好像不是这样用吧!
__autoload 函数只有当 new ClassName 并且不存在 类 ClassName 时,系统就自动调用 __autoload ,这个函数有一个参数就是 类名称 然后在这个函数里定义 查找类的执行代码并包含进去。
参考资料:www.oscodes.net
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/865616.htmlTechArticlePHP管理依赖(dependency)关系工具 Composer的自动加载(autoload),dependencyautoload 举例来说,假设我们的项目想要使用 monolog 这个日志工具,就需...
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP的當前狀態:查看網絡開發趨勢PHP的當前狀態:查看網絡開發趨勢Apr 13, 2025 am 12:20 AM

PHP在現代Web開發中仍然重要,尤其在內容管理和電子商務平台。 1)PHP擁有豐富的生態系統和強大框架支持,如Laravel和Symfony。 2)性能優化可通過OPcache和Nginx實現。 3)PHP8.0引入JIT編譯器,提升性能。 4)雲原生應用通過Docker和Kubernetes部署,提高靈活性和可擴展性。

PHP與其他語言:比較PHP與其他語言:比較Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP與Python:核心功能PHP與Python:核心功能Apr 13, 2025 am 12:16 AM

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP:網絡開發的關鍵語言PHP:網絡開發的關鍵語言Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP:許多網站的基礎PHP:許多網站的基礎Apr 13, 2025 am 12:07 AM

PHP成為許多網站首選技術棧的原因包括其易用性、強大社區支持和廣泛應用。 1)易於學習和使用,適合初學者。 2)擁有龐大的開發者社區,資源豐富。 3)廣泛應用於WordPress、Drupal等平台。 4)與Web服務器緊密集成,簡化開發部署。

超越炒作:評估當今PHP的角色超越炒作:評估當今PHP的角色Apr 12, 2025 am 12:17 AM

PHP在現代編程中仍然是一個強大且廣泛使用的工具,尤其在web開發領域。 1)PHP易用且與數據庫集成無縫,是許多開發者的首選。 2)它支持動態內容生成和麵向對象編程,適合快速創建和維護網站。 3)PHP的性能可以通過緩存和優化數據庫查詢來提升,其廣泛的社區和豐富生態系統使其在當今技術棧中仍具重要地位。

PHP中的弱參考是什麼?什麼時候有用?PHP中的弱參考是什麼?什麼時候有用?Apr 12, 2025 am 12:13 AM

在PHP中,弱引用是通過WeakReference類實現的,不會阻止垃圾回收器回收對象。弱引用適用於緩存系統和事件監聽器等場景,需注意其不能保證對象存活,且垃圾回收可能延遲。

解釋PHP中的__ Invoke Magic方法。解釋PHP中的__ Invoke Magic方法。Apr 12, 2025 am 12:07 AM

\_\_invoke方法允許對象像函數一樣被調用。 1.定義\_\_invoke方法使對象可被調用。 2.使用$obj(...)語法時,PHP會執行\_\_invoke方法。 3.適用於日誌記錄和計算器等場景,提高代碼靈活性和可讀性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用