当前位置:首页 > > 充电吧
[导读]Composer 是PHP的一个包依赖管理工具,类似Ruby中的RubyGems或者Node中的NPM,它并非官方,但现在已经非常流行。此文并不介绍如何使用Composer,而是关注于它的autolo

Composer 是PHP的一个包依赖管理工具,类似Ruby中的RubyGems或者Node中的NPM,它并非官方,但现在已经非常流行。此文并不介绍如何使用Composer,而是关注于它的autoload的内容吧。

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

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

之后执行:

php composer.phar install

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

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

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

use MonologLogger;
use MonologHandlerStreamHandler;

// 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的代码吧

 $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;
}


如此最终实现的原理是在vendor目录下的


return ComposerAutoloaderInit5cbf6bb00ad8ca1716a58cda814c22a3::getLoader();

在getLoader中为ComposerAutoloadClassLoader();类填充了信息包括psr-0 psr-4等自动加载机制所需的消息然后调用

ComposerAutoloadClassLoader()的register函数,进行sql_autoload_register的调用,这样之后每当进行类加载的时候
依次在 psr4前缀中进行查找文件目录,在psr4 fallback目录中查找,在psr0前缀中查找目录,在psr0 fallback中查找还有就是在psr0 include path中进行查找文件




本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
换一批
延伸阅读

LED驱动电源的输入包括高压工频交流(即市电)、低压直流、高压直流、低压高频交流(如电子变压器的输出)等。

关键字: 驱动电源

在工业自动化蓬勃发展的当下,工业电机作为核心动力设备,其驱动电源的性能直接关系到整个系统的稳定性和可靠性。其中,反电动势抑制与过流保护是驱动电源设计中至关重要的两个环节,集成化方案的设计成为提升电机驱动性能的关键。

关键字: 工业电机 驱动电源

LED 驱动电源作为 LED 照明系统的 “心脏”,其稳定性直接决定了整个照明设备的使用寿命。然而,在实际应用中,LED 驱动电源易损坏的问题却十分常见,不仅增加了维护成本,还影响了用户体验。要解决这一问题,需从设计、生...

关键字: 驱动电源 照明系统 散热

根据LED驱动电源的公式,电感内电流波动大小和电感值成反比,输出纹波和输出电容值成反比。所以加大电感值和输出电容值可以减小纹波。

关键字: LED 设计 驱动电源

电动汽车(EV)作为新能源汽车的重要代表,正逐渐成为全球汽车产业的重要发展方向。电动汽车的核心技术之一是电机驱动控制系统,而绝缘栅双极型晶体管(IGBT)作为电机驱动系统中的关键元件,其性能直接影响到电动汽车的动力性能和...

关键字: 电动汽车 新能源 驱动电源

在现代城市建设中,街道及停车场照明作为基础设施的重要组成部分,其质量和效率直接关系到城市的公共安全、居民生活质量和能源利用效率。随着科技的进步,高亮度白光发光二极管(LED)因其独特的优势逐渐取代传统光源,成为大功率区域...

关键字: 发光二极管 驱动电源 LED

LED通用照明设计工程师会遇到许多挑战,如功率密度、功率因数校正(PFC)、空间受限和可靠性等。

关键字: LED 驱动电源 功率因数校正

在LED照明技术日益普及的今天,LED驱动电源的电磁干扰(EMI)问题成为了一个不可忽视的挑战。电磁干扰不仅会影响LED灯具的正常工作,还可能对周围电子设备造成不利影响,甚至引发系统故障。因此,采取有效的硬件措施来解决L...

关键字: LED照明技术 电磁干扰 驱动电源

开关电源具有效率高的特性,而且开关电源的变压器体积比串联稳压型电源的要小得多,电源电路比较整洁,整机重量也有所下降,所以,现在的LED驱动电源

关键字: LED 驱动电源 开关电源

LED驱动电源是把电源供应转换为特定的电压电流以驱动LED发光的电压转换器,通常情况下:LED驱动电源的输入包括高压工频交流(即市电)、低压直流、高压直流、低压高频交流(如电子变压器的输出)等。

关键字: LED 隧道灯 驱动电源
关闭